I am just learning the software for Arduino and have been following the course by Paul McWorter. I got to his lesson 7 and wrote the code for the while loops in the lesson.
When testing the code, the first while loop waited for input but then blew right past the second while loop.
After a frustrating search to find my mistake, I finally just copied the code from his lesson and the result is the same.
I think his lessons were presented in 2014 or so and I am wondering if the compiler or hardware has changed.
Here is the code:
Serial.println("How Many Times Do You Want the Red LED to Blink? "); //Prompt User for Input
while (Serial.available()==0){ } //Wait for User Input
numRedBlinks = Serial.parseInt(); //Read User Input
Serial.println("How Many Times Do You Want the Yellow LED to Blink? "); //Prompt User for Input
while (Serial.available()==0){ } //Wait for Input
numYellowBlinks = Serial.parseInt(); //Read User Input
I don't know this course, but if you are sending CR and LF after your number, they will still be in the buffer when you hit the second while (Serial.available()==0){ } //Wait for Inputso you will proceed right away to numYellowBlinks = Serial.parseInt();and those functions have a 1 second timeout by default, so if you don't type anything it will move on
Not sending anything at the end of the line will make the first parseInt() return the value after timeout and nothing will be left in the incoming buffer, so you'll be waiting at the while() until something else comes in - which is the desired behavior.
This is not a great way to read the Serial line, but good for a start
Always purge the input buffer before you wait for input. This fixes not only the line endings but also protects against any extra characters typed between the number and hitting 'Return'.
Serial.println("How Many Times Do You Want the Red LED to Blink? "); //Prompt User for Input
while (Serial.available(){Serial.read();} // Clear the input buffer
while (Serial.available()==0){ } //Wait for User Input
numRedBlinks = Serial.parseInt(); //Read User Input
johnwasser:
Always purge the input buffer before you wait for input.
Well that’s not great either because in the example above if I input in the serial console right away “100 200” and validate, that should work fine and both integer would be read, the space acts as a separator for parseInt
Ideally there are either start marker and or an end marker or both to help with a serial communication