Calculating Time That Has Elapsed Without Rollover Effect??

Hi,

im a little worried about the effects of millis() rollover when im trying to calculate the time that has elapsed during a process. Perhaps im a little over worried???

Basically what id like to do is:

  1. initialize a timer.
  2. wait for serial input to match some given criteria.
  3. if criteria matches then reset the timer,
    else if the timer is greater then some interval (say 10 seconds) then flip the state on a "timeout" flag.

So thought of doing something like this (non-functional code ahead):

#define timeout 10000
int timer = millis();
boolean connectFlag = false;
void loop() {
    if (Serial.available() != 0) {
        int myChar = Serial.read();
        appendBuffer(myChar); // builds a buffer from serial input
        if (myChar == 13)  { 
            if (checkBuffer() == true)  { // check the buffer after char 13 received   
                timer = millis(); // SUCCESS, so we now need to reset the timer.
                connectFlag = true; // sets a flag to indicate the device connected
            }
        clearBuffer(); // clears the buffer after char 13 received   
        }    
    }  else if (millis() >= timer + timeout) { // device did not respond in a timely manor so change the connectFlag to false
        timer = millis(); // FAILED, we will reset the timer anyways.
        connectFlag = false;
    }
}

could this method pose a vulnerability to millis() rollover? and if so, how could one rectify this to be a little safer??

Thanks!!

Look at the blink without delay example. That uses a subtraction method an it works even through roll over which happens once every 50 odd days of continuous running.

Yes. If you store a time as "unsigned long savedTime = millis() and later measure the elapsed time using "millis() - savedTime" you will get the correct answer even through a rollover. The beauty of binary maths.

...R