Get string from serial port with timeout

As you point out, the function is blocking, so move the body of the function code into the main loop.

Most people choose to terminate the input string and take action when a CR or other suitable line terminator is reached, rather than use a timeout. But use a timeout if you wish.

The Serial Input Basics tutorial might be helpful.

Another approach is to rewrite the function so that it returns immediately if no character is waiting to be added to the input string, or continues, then returns a value that indicates whether an entire line was successfully input, or a timeout occurred. An example is the TinyGPS++ library, which reads and interprets a GPS serial stream using non-blocking code.

1 Like