While Loop

First of all I want to say I am new in Arduino and C.

I have the below code to read the UART input, but, I want to go out of the "While" loop if not receive data within 2 seconds. I know that we can use "millis" and another "while loop", or another solution that I am not seeing now, but, I do not know how to do it.

Can you please help me. thanks, Manuel

        ;// Do nothing until there is something to read  
        received_byte = Serial.read();

Serial available returns an int, don’t treat it as a bool , can cause unexpected side effects.

unsigned long lastTime = millis();
while (Serial.available() == 0 && millis() - lastTime < 2000); // Do nothing until there is something to read  or 2000 milliseconds have passed

if (Serial.available() > 0) // if there is something to read 
   received_byte = Serial.read();  // read it 
  // process the byte
  // nothing read code

give it a try

Rob Tillaart,

Thanks for the help. I am going to try it.


"Serial available returns an int" Really? I thought it was a byte. I've always treated it a byte and it seemed to work that way.

from the libs

int HardwareSerial::available(void)
  return (unsigned int)(RX_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % RX_BUFFER_SIZE;

but as the buffer is small (RX_BUFFER_SIZE = 32 or 128) a byte will work too

But I can imagine that in a future version, or on bigger RAM avr's the default buffersize could increase or that special values will be used e.g. for buffer overflow conditions. needs some additional code but possible.

Don't know the new serial code of the 1.0 libs ...