Search code examples
arduinoarduino-c++

(Serial.available() > 0) waits for user input


I'm facing problem with user input in Arduino ide. I would like arduino to periodically check if user generate some input string (arduino checks it every 3 seconds), but even if there is no input after 3 seconds (string order="") arduino waits for user input and when I type something then it exit "checkIncomingOrder" function and wait another 3 seconds. I would be gratefull for any advice. My simple code is below:

String order = "";
int timer;

void setup() {
  Serial.begin(9600);
  timer = 0;
}

void loop() {
  if (timer == 3)
  {
    checkIncomingOrder();
  }
  else
  {
    delay(1000);
    Serial.println("waiting");
    timer++;
  }
}

void checkIncomingOrder() {
  if (Serial.available() > 0) { 
    order = Serial.readStringUntil('\n'); 
  }
  if (order == "") {
    return;
  } else {
    Serial.println("Order is: " + order); 
    order = "";
    timer = 0;
  }
}

Solution

  • Serial::Available() does not block. If there are characters available, readStringUntil() will be called, but that will not return until a newline is available - so that is where your blocking on input is likely to be occurring.

    The following is perhaps a safer non-blocking solution:

    void checkIncomingOrder() 
    {
        char ch = 0 ;
        while( ch != '\n' && Serial.available() > 0 ) 
        { 
            Serial.readBytes( &ch, 1 ) ; 
            order += ch ;
        }
    
        if( ch == '\n' ) 
        {
            Serial.println("Order is: " + order) ; 
            order = "" ;
            timer = 0 ;
        }
    }
    

    It allows you to check for a line of input continuously rather then every three seconds - making the solution more responsive:

    void loop() 
    {
        checkIncomingOrder();
    }
    

    allowing in turn the timer variable to be removed.