char dat;
long time_is_up;
char flag = 0;
void setup()
{
Serial.begin(9600);
time_is_up = millis();
time_is_up += 2000; // 2000 millis = 2 seconds
}
void loop()
{
if(flag == 0) // run the checks below each time through the loop if flag = 0
{
if( time_is_up > millis() ) // check if 2 seconds has elepsed
if(Serial.available() > 0) // if under 2 seconds and if serial data is available
dat = Serial.read(); // read the serial data
if( time_is_up < millis() ) // if 2 seconds has passed
{
flag = 1; // turn the flag off so the checks won't be run any more.
Serial.end(); // turn off Serial here so it is off if millis rolls over after 4,294,967,295 milliseconds.
}
}
// do something with the dat read, or whatever else here.
}