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);
-
1That'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– Chris Stratton2018年02月19日 17:44:01 +00:00Commented Feb 19, 2018 at 17:44
1 Answer 1
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:
And remember: code doesn't manage any error condition; is up to you.
-
and the Stream.parseInt() function? it uses Stream.setTimeout() setting2018年02月19日 13:16:10 +00:00Commented Feb 19, 2018 at 13:16
-
@Juraj, to keep the sketch going and use non-blocking is far more important.Jot– Jot2018年02月19日 13:27:40 +00:00Commented Feb 19, 2018 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 likedelay
user31481– user314812018年02月19日 13:28:37 +00:00Commented Feb 19, 2018 at 13:28 -
true. parse and waitUntil functions can't be used with user input.2018年02月19日 13:32:26 +00:00Commented Feb 19, 2018 at 13:32