Using millis in alarm system

So long as, when you need to check if a certain interval has past, you use something like

if(currentTime - previousTime > interval)

and both times are defined as unsigned long then you will not experience any issues.

After 49 something days millis will rollover, and therefore currentTime could actually be less than previousTime, but the subtraction statement above also effectively rolls over so it actually produces the correct result - that is, it will return the number of milliseconds between the times.

Compare that to the statement below

if(currentTime > previousTime + interval)

although this looks logically similar, you can see that in some cases this will not work. Specifically, when currentTime has rolled over, but previousTime + interval does not cause a rollover.

1 Like