Safe millis with rollover compensation

From Public Wiki
Revision as of 02:38, 9 December 2020 by Legg (talk | contribs) (Created page with "==Synopsis== Demonstrate safe delays with millis() or micros() that has rollover compensation. ==Notes== ==Code== <syntaxhighlight lang="C++" line='line'> // Interval is h...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Synopsis

Demonstrate safe delays with millis() or micros() that has rollover compensation.

Notes

Code

 1 // Interval is how long we wait
 2 // add const if this should never change
 3 int interval=1000;
 4 // Tracks the time since last event fired
 5 unsigned long previousMillis=0;
 6  
 7 void setup() {
 8    pinMode(13, OUTPUT);
 9 }
10  
11 void loop() {
12    // Get snapshot of time
13    unsigned long currentMillis = millis();
14  
15    // How much time has passed, accounting for rollover with subtraction!
16    if ((unsigned long)(currentMillis - previousMillis) >= interval) {
17       // It's time to do something!
18       digitalWrite(13, !digitalRead(13)); // Toggle the LED on Pin 13
19  
20       // Use the snapshot to set track time until next event
21       previousMillis = currentMillis;
22    }
23 }