Go to main loop

I am trying to implement a waiting period when the user can input a number via the Serial Monitor but if they don’t enter anything within a certain time the script continues using defaults.

I have implemeted the inputs with:

while(Serial.available() == 0);
  set = Serial.read();
  if (set == '1'){
    Do something
  if (set == '2'){
    Do something else

That works just fine. I now need to implement the timer. At first I tried this:

Serial.println("Enter (1), (2), (3) or (4)continue");
  unsigned long counter = millis(); // set counter variable
  while(Serial.available() == 0);
  if(counter > 20000){}
  set = Serial.read()........;

But that doesn’t work. I tried putting loop() in the if parantheses but that doesn’t work either. Finally I tried “while(counter < 20000);” again without success.

What am I missing here?

I would use millis timing.

If time has passed and no user info
use code info

First of all you should mind where you put your ";" since this means "end of statement":

while(Serial.available() == 0);

This will block (indefinitely or) until there is something available to read from serial while it does nothing.

If you want to use millis() for timing, read this.

As a quick and dirty solution you could use Serial.readBytes() and set the timeout using the Serial.setTimeout() function. You will, however, learn a lot more by reading in a loop until either a character is received or the required period has elapsed timed using millis()

Thanks for the replies. I removed the while(Serial.available() == 0); and replaced it with a while loop using millis(). Everything is working fine now.