Go Down

Topic: Newbie problem with: while(Serial.available)==0) { } (Read 120 times) previous topic - next topic

geone

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

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. 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():
Code: [Select]
delay(10);  // wait for all the serial data to arrive
// clear the Serial receive buffer
while (Serial.available() > 0) {
  Serial.read();
}

Robin2

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
Two or three hours spent thinking and reading documentation solves most programming problems.

geone

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

GolamMostafa

#4
Feb 18, 2020, 06:11 am Last Edit: Feb 18, 2020, 06:12 am by GolamMostafa
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.

Figure-1: Serial Monitor

Go Up