Using millis in alarm system

I am doing rather simple alarm system with two loops and 5 PIR sensors to my garage with simple pushbuttons to turn alarm on or off. I have everything sorted and coded out but I started to think that will using millis() for calculating time in such project which will be on continuously for long periods, cause any problems? Especially one function what I want which will turn alarm on if no sensor has been active or doors open for 6 hours.

I have read that millis will jump back to zero for every 50 days or so. Will this cause any problems for my project to take consider? Any other solutions?

millis()-sometimepast >= someTimeInterval works

sometimepast-millis() >= someTimeInterval does not work well.

Just a simple matter of ordering the formula to handle the overflow issue.

Hi, welcome to the forum.

The millis() function can be used to blink a led, to calculate how long something takes and so on.
When done right, it will work perfectly fine, even during a rollover (when millis goes from 0xFFFFFFFF to 0x00000000).

If your garage door is not opened for months and you want to measure how long it has not been used, then you add a Real Time Clock (RTC) and calculate the time in days (or in hours or seconds or so).

The Blink Without Delay is the introduction to millis().

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

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.