Best practive for system timing in loop()

Hi guys,

whats the best solution for system timing. I have following solutions currently:

// Programm timers
unsigned long _t100cL = 0; // Last 100cycles call

void loop() {
  
    // 100ms System calls
    if (millis() - _t100msL > 100) {
        
        // Do smth every 100 calls

        _t100msL = millis();
    }
}

Or by modulo:

void loop() {
  
    if (millis() % 100 == 0) {
        // Do smth every 100 calls

    }
}

Maybe an own counter could be faster that the millis() call. Or how do you guys handle it?

Best greetings
Raphael

Using ">=" would be preferable.

If it is a short sketch, then call it "previousMillis", so we can recognize it as a millis-timer.
The Blink Without Delay uses "previousMillis".

!< u :heart: :crazy_face: :name_badge:
Translated: un-less you like crazy names

If you do (millis() % 100 == 0) then it may never happen, since there is a correction for the time. Some values are never returned by millis(). If the code in the loop() takes some time, then that moment could be missed. It is therefor wrong code in two ways.

There are more ways to use millis(). The best is to stay with the Blink Without Delay example.

Hello
I´m using

digitalWrite(LED_BUILTIN, (currentTime / 500) % 2);

as heartbeat indicator of a running sketch.

Have a nice day and enjoy coding in C++.

Using modulo adds an unnecessary amount of library code…
Try it both ways and look at the flash requirements !

I use the MoToTimer part of my MobaTools library. There is a class MoToTimebase to execute something in regular intervals. An example is in Timebase01.ino
I don't like to deal with basics over and over again. You solve that once and then you can concentrate on the real tasks :wink:

WARNING! The function millis() doesn't always increment by 1. Sometimes it increments by 2. Any test that looks for an exact value of millis() will likely miss that count periodically.

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