Go Down

Topic: adding time-out to serial port (Read 5982 times) previous topic - next topic


Thank you for reading this.

I want to add a time-out period to prevent Arduino's serial port waiting forever for data from the host computer. This option does not seem to be available. Is there a way to add a time-out period? A Google search has not located an answer.



Arduino serial library does not 'block' (wait forever) on receiving data, it's interrupt driven. You can just test for data being avalible or not:




Note that the SoftwareSerial library doesn't offer the Available function, but that NewSoftSerial does. (SS part of standard distribution, NSS avail from main Arduino site).

These are both for if you want to do serial comms on pins other that the "standard" ones that your programming link works over.


Are you using SoftwareSerial, and it's read() is blocking you, or are you using hardware serial, and attempting to read a specified length of data via a while loop?

If the latter, you can do something like this:

Code: [Select]

  // clear out any previous command data
memset(input_serial_buffer, 0, sizeof(char) * SER_COM_BUFFER_LEN);

serial_time = millis();

  // populate command data buffer
for( int i = 1; i <= com_byte_count; i++ ) {
    // get com_byte_count character values from the serial
    // buffer
      // wait until we have data ready
    while( ! Serial.available() ) {
      if( millis() - serial_time > SERIAL_TIMEOUT ) {
        // timed out waiting for complete input
            // send 'fail' response
        return( 0 );  
    input_serial_buffer[i - 1] = (byte) Serial.read();    

Go Up