0
votes

I need to read in exactly 1 three digit integer (example: 134) from the serial monitor. I am currently using Serial.parseInt() and getting the behavior I want, but it is very slow. What would be a faster alternative to this method?

Edit: All parts of the integer must be read in at the same time, so using Serial.available() and Serial.read() is not an option.

Edit2: I attempted using

while (Serial.available()) {
  int val = Serial.read();
  int val2 = Serial.read();
  int val3 = Serial.read();
  Serial.print("Val1: ");
  Serial.println(val);
  Serial.print("Val2: ");
  Serial.println(val2);
  Serial.print("Val3: ");
  Serial.println(val3);
}

In the loop portion, but got the output

Val1: 97
Val2: -1
Val3: -1
Val1: 98
Val2: -1
Val3: -1
Val1: 99
Val2: -1
Val3: -1

when I typed abc into the serial monitor.

1
Why is Serial.available() and Serial.read() not an option?Programmer
I edited the post to explain the problems I was having with it.Marjoram
Don't do it that way. Only have one Serial.read() in your Serial.available() loop.You have triple of those and that's not good. Where are you typing abc?Programmer
I apologize for not knowing the technical name, but the place where you type characters into the serial monitor. If I only have one Serial.read() in a Serial.available() loop and I need to read in 3 numbers, how do you suggest that I do this? Have 3 separate Serial.available() loops? I feel like this could introduce some subtle timing errors into the program....Marjoram
This is how Serial.read works. When you have 3 bytes to read(a,b,c), the Serial.available will be true until all bytes are read. So, if you have one int val = Serial.read(); inside Serial.available, it will run three times then the loop will become false and exist. Try that and let me know what problem you are having. Are you using the Arduino Serial monitor to send the bytes?Programmer

1 Answers

1
votes

It's okay to use Serial.parseInt.

For me, in my setup function

  //this will allow the parseInt to read faster and 
  //the arduino board will responsd faster
  Serial.setTimeout(50);   

This is because parseInt() will continue to read from serial until either
it reaches a non-integer value e.g. alphabet, or
the serial timeouts.