Serial.setTimeout() sets the maximum milliseconds to wait for serial data. It defaults to 1000 milliseconds.
Serial.setTimeout() inherits from the Stream utility class.
Use the following function to set the serial time-out.
Serial.setTimeout(time)
The function admits the following object and parameter:
Serial: serial port object. See the list of available serial ports for each board on the Serial main page.
time: timeout duration in milliseconds. Allowed data types: long.
The function returns nothing.
The following code modifies the default serial timeout time:
char data[6]; // 5 characters + null terminator
void setup() {
Serial.begin(9600);
while (!Serial);
Serial.setTimeout(5000); // Set timeout to 5 seconds
Serial.println("Send 5 characters (you have 5 seconds):");
}
void loop() {
if (Serial.available()) {
int bytesRead = Serial.readBytes(data, 5);
data[bytesRead] = '\0';
Serial.print("Received: ");
Serial.println(data);
}
}
Serial functions that use the timeout value set via Serial.setTimeout():
Serial.find()Serial.findUntil()Serial.parseInt()Serial.parseFloat()Serial.readBytes()Serial.readBytesUntil()Serial.readString()Serial.readStringUntil()