Pages: [1]   Go Down
Author Topic: adding time-out to serial port  (Read 2534 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 8
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.

Regards,
Phil
Logged

Left Coast, CA (USA)
Offline Offline
Brattain Member
*****
Karma: 361
Posts: 17294
Measurement changes behavior
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:

http://arduino.cc/en/Serial/Available

Lefty
Logged

Sussex UK / CT USA
Offline Offline
Edison Member
*
Karma: 0
Posts: 1028
Forums forever
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

0
Offline Offline
Sr. Member
****
Karma: 4
Posts: 323
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
  // 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
         serial_write((byte)0);
         serial_write((byte)0);
         return( 0 );  
       }
     }
    
     input_serial_buffer[i - 1] = (byte) Serial.read();    
 }
Logged

Pages: [1]   Go Up
Jump to: