marcelloromani / Arduino-SimpleTimer

27 stars 47 forks source link

What happens when millis overflows? #13

Open rmetcalf9 opened 6 years ago

rmetcalf9 commented 6 years ago

According to https://www.arduino.cc/reference/en/language/functions/time/millis/ the value returned by millis will overflow after about 50 days.

On this page: https://playground.arduino.cc/Code/SimpleTimer you state your algroythm is:

lastMillis = 0
forever do:
    if (millis() - lastMillis > n)
        call the particular piece of code
        lastMillis = millis()
    end
end

Which means that after millis overflows, millis() - lastMillis can never be greater than n since millis is now 0. This means that after 50 days any timers will simply stop running.

In my application I want a timer to run every 2 hours. Reading all the docs about this code it is not clear to me if this is true. Can you edit your docs to either state that this library will not work after 50 days, or state that the library has code that will enable a regular timer to continue working.

sebi008 commented 5 years ago

http://arlotto.univ-tln.fr/arduino/article/utilisez-correctement-la-fonction Sorry it's in french but the fact is a mcu doesn't make operation like a human beeing. (I try to make a summary ) the internal logic can not make directly X-Y but uses binary operations. In binary to make X-Y you have to make X + (-Y) (thanks cap'tain obvious but the difference is significant) 0 - 0xFFFF9E58 = -0xFFFF9E58 or -0xFFFF9E58 = logical inverse of 0xFFFF9E58 +1 = 0x000061A7+1 =0x000061A8 = 25000 so when you have millis=5000 and you want 30s timeout, the last tick was at 4294942296, you have 5000 - 4294942296 = 0x00001388 - 0xFFFF9E58 = 0x00013880 + 0x000061A8 = 0x00007530 = 30000 so this library works as expected

rmetcalf9 commented 5 years ago

Thank you for the explanation. As someone who had not looked into it in detail but had found articles that millis would overflow after 50 days I think it would be good if the fact it has been considered and resolved was referenced in the documentation.

If the theory section at https://playground.arduino.cc/Code/SimpleTimer was altered to add a note, something like:

(Millis will over flow after 50 days and this code will continue to work due to the way the processor subtracts numbers.)

I think this would be helpful especially since I am sure many people looking to use the library will be working on projects designed to be running for more than 50 days and will be worried like I was.

marcelloromani commented 5 years ago

I agree. I haven't looked at this issue in quite a while, but feel free to add a note in the SimpleTimer page yourself.