// comparison of BWOD/millis() periodic timing methods
// https://wokwi.com/projects/408208115408659457
// for https://forum.arduino.cc/t/waiting-1-5-of-a-second-in-a-program/1298515
// This prints the ms timestamp of each non-blocking periodic timer
// along with a count of activations
//
// Cause a block by shorting the blockPin
// Slow the loop with a delay per the delayPot
const uint32_t interval = 200;
uint32_t now = 0;
const byte blockPin = 2;
const byte delayPot = A0;
void setup() {
Serial.begin(115200);
pinMode(blockPin, INPUT_PULLUP);
}
void loop() {
// put your main code here, to run repeatedly:
now = millis();
periodicAssign();
periodicAdd();
periodicSkip();
delayMicroseconds(analogRead(delayPot)*4);
while (digitalRead(blockPin) == LOW) {;}
}
// update by assigning the current time
// vulnerability: delays and blocks cause slewing
void periodicAssign() {
static uint32_t last = 0;
static uint32_t count = 0;
if (now - last >= interval) {
++count;
last = now;
Serial.print(now);
Serial.print("\t");
Serial.print("Assign: ");
Serial.println(count);
}
}
// update by stepping the last time forward
// vulnerability: small delays cause a phase lag, huge delays and blocks cause multiple triggers
void periodicAdd() {
static uint32_t last = 0;
static uint32_t count = 0;
if (now - last >= interval) {
last += interval;
++count;
Serial.print(now);
Serial.print("\t");
Serial.print("Add: ");
Serial.println(count);
}
}
void periodicSkip() {
// vulnerability: a bit more overhead, stays in phase with millis()
static uint32_t last = 0;
static uint32_t count = 0;
if (now - last >= interval) {
while (now - last >= interval) {
last += interval;
}
++count;
Serial.print(now);
Serial.print("\t");
Serial.print("Skip: ");
Serial.println(count);
}
}Delay 0-4092us/loop()
Block