I am working on a sketch that requires user input within the "void loop(){}". I thought that I could halt program execution using some boolean variables and while statements.
The desired functionality (inside the loop() function) is as follows:
- wait for user input
- when user input is detected, print something
- wait for a second user input
- when user input is detected, print something else
- end (no printing upon further iterations of "loop()")
Here's my code:
boolean flag = false;
boolean isWaiting1 = true; // wait for user input 1
boolean isWaiting2 = true; // wait for user input 2
void setup()
{
Serial.begin(9600); // begin serial comm
}
void loop()
{
while(isWaiting1 == true) // enter user input 1 block
{
while (flag == false) // enter "monitor" loop
{
while(Serial.available() == 0){} // continuously monitor serial port for any data;
Serial.println ("A"); // if (Serial.avaialable != 0) then print "A"
flag = true; // break while(flag == false)
}
flag = false; // reset flag
isWaiting1 = false; // break while(isWaiting1 == true)
}
delay(1000); // wait 1 second
while(isWaiting2 == true) // enter user input 2 block
{
while (flag == false) // enter "monitor" loop
{
while(Serial.available() == 0){} // continuously monitor serial port for any data;
Serial.println ("B"); // if (Serial.avaialable != 0) then print "B"
flag = true; // break while(flag == false)
}
flag = false; // reset flag
isWaiting2 = false; // break while(isWaiting2 == true)
}
}
I should mention that I am using a Teensy 3.1 on Arduino 1.0.6 (w/ Teensyduino 1.21-test)
What ends up happening with this sketch is it will...
- wait for the first user input
- detect it upon sending something to the serial monitor
- does not wait for the second user input
- proceeds to print without waiting
- end
I suspect that the issue stems from the following line of code:
while(Serial.available() == 0){} // continuously monitor serial port for any data;
It seems that after the first user input the line of code above is not TRUE; which explains why there is no waiting for the second user input. I tried manually assigning "Serial.avaiable()" to zero after receiving the first user input, but to no avail. Also tried using flush() and memset(). No luck. Any guidance would be much appreciated!