Hi,
This has likely been asked before, but I could not seem to find an answer that makes sense to me.
My code works, but I'm concerned what would happen at rollover time. I do need my program to run continuously and will be active more than 50 days and I want to make sure I'm coding in the best possible way.
In my program I have many timers. For example after x number of seconds of inactivity, turn off the lights to save power.
I would normally code it like this.
unsigned long SleepTime = millis()+LightsOffTime;
if (millis() >= SleepTime) // If sleep timer exceeded
LightsOff();
This works fine, but what happens when close to overflow, when my addition of the LightsOffTime overflows the unsigned long int value?
I've seem the most people seem to code using subtraction rather than addition as I'm doing
unsigned long SleepTime = millis()
If (millis() - SleepTime > LightsOffTime)
LightsOff();
To me this has the same issue. If the clock has just rolled over millis() would return a tiny number and I would attempt to subtract a huge number from it resulting in a negative number. Since the field is an unsigned long I would think that would yield some type of nasty error.
What's the correct way to code for this without having a real time clock?
Thanks!