Newbie problem with: while(Serial.available)==0) { }

Newbie has a problem with the following: this code wants to read an INT value for two questions and then do something.

Serial.println("how many red blinks?");
while(Serial.available()==0) { }
redlednum=Serial.parseInt();

Serial.println("how many green blinks?");
while(Serial.available()==0) { }
greenlednum=Serial.parseInt();

the first Serial.available works fine (asks question, waits until the value is received and goes to the second question. Then the second completes the Serial.println but ignores the second while(Serial.available()==0) { }

thanks for any help

To make your code work as expected, you need to select "No line ending" from the line ending menu near the bottom right corner of Serial Monitor. If you have another line ending selected, then the numbers you sent are parsed as an int by the first call to Serial.parseInt(), but the line ending is left in the Serial receive buffer, so the next call to Serial.available() returns a value greater than 0 and the next call to Serial.parseInt() tries to parse the line ending as an int, which can't be done, so it returns 0.

You can modify your code to handle any line ending by clearing the Serial receive buffer with this code after Serial.parseInt():

delay(10);  // wait for all the serial data to arrive
// clear the Serial receive buffer
while (Serial.available() > 0) {
  Serial.read();
}
1 Like

Getting user input reliably is one of the trickier programming challenges.

There is a simple user input example in Planning and Implementing a Program

...R

thanks for the help...I will give it a shot
again, thanks much

pert:
To make your code work as expected, you need to select "No line ending" from the line ending menu near the bottom right corner of Serial Monitor.

@OP
This is the layout of the Serial Monitor (Fig-1) pf Arduino IDE.
SerialMonitor.png
Figure-1: Serial Monitor

SerialMonitor.png