0

Is is possible to read from serial window till timeout?

Actually, what I am looking for is a function that reads from serial monitor, and if no data is available in serial monitor, then it should wait for some time and if still no data is arrived it should return.

Something like,

Serial.read(int timeout);
1
  • 1
    That's nearly what Serial.readString() does, only you have to set the timeout in advance. However, such an approach may or may not be what is best for your ultimate goals. – Chris Stratton Feb 19 '18 at 17:44
2

Use this:

byte x;
if (Serial.available() > 0) {
  x = Serial.read();
  }

This doesn't block, because you only read when there is something available in the input buffer.

Now, if you want to read an integer with time-out the serial input, this is a short demo:

#define TIME_OUT 10000L
void setup()
{
    Serial.begin(9600);

    while(!Serial);

    Serial.println();

    Serial.println("Input an int (waiting for 60 seconds");
}

void loop()
{
    static unsigned long timeLastInput = 0;
    unsigned long now = millis();
    static char buffer[10];
    static int index = 0;
    int value;

    if(Serial.available() > 0) {
        char x = Serial.read();
        timeLastInput = now;

        if(isDigit(x)) {
            buffer[index++] = x;
        } else {
            if(index > 0) {
                buffer[index] = 0;
                value = atoi(buffer);
                Serial.print("Integer=");
                Serial.println(value);
                index = 0;
            }
        }
    }

    if(now - timeLastInput > TIME_OUT) {
        Serial.println("Time out");
        index = 0;
        timeLastInput = now;
    }
}

It works by reading all digits into buffer. A non digit input signal the end of the integer. We use atoi to convert the integer ascii representation in his binary value. The result you wants is stored in the value variable.

Note that we read only one char at the time in each loop pass.

And this how the output looks:

enter image description here

And remember: code doesn't manage any error condition; is up to you.

4
  • and the Stream.parseInt() function? it uses Stream.setTimeout() setting – Juraj Feb 19 '18 at 13:16
  • @Juraj, to keep the sketch going and use non-blocking is far more important. – Jot Feb 19 '18 at 13:27
  • @Juraj. I want to do other things beside sitting waiting for an integer to come. The generic problem with setTimeout() is that if too short, doesn't work, and if it is too long, you missed other events and maybe even get a watchdog reset. The proposed solution can wait for hours without blocking. setTimeout is like delay – user31481 Feb 19 '18 at 13:28
  • true. parse and waitUntil functions can't be used with user input. – Juraj Feb 19 '18 at 13:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.