// https://wokwi.com/projects/327585926943343186
// sketch for https://forum.arduino.cc/t/having-difficulty-with-subtration-of-unsigned-long/974685/
// Try F1 "View Compiled Assembly Code" to see the implementation
// Each of these if-clauses periodically triggers and prints a character
// to the serial monitor.
// Note the begining of the output with the "Ae" These two patterns
// make an immediate match, whikle the others all trigger at the end
// of the first period
// common variables for loop() and other functions
const uint32_t interval = 254; // common interval 254 for byte-sized B
unsigned long now = millis();
void setup() {
Serial.begin(115200);
}
void loop() {
now = millis();
// normal way, after each interval
static unsigned long last = 0;
if (now - last >= interval ) {
Serial.print(" N");
last += interval;
}
// compare absolute timestamps way:
// (future scheduing)
static unsigned long next1 = 0;
if ((signed long)(now - next1) >= 0 ) {
Serial.print('A');
next1 += interval;
}
// normal way, before first and after each interval:
static unsigned long last1 = -interval;
if (now - last1 >= interval ) {
Serial.print('e');
last1 += interval;
}
// compare absolute timestamps way:
// (future scheduing)
static unsigned long next2 = interval;
if ((signed long)(now - next2) >= 0 ) {
Serial.print('a');
next2 += interval;
}
// ############### smaller size intervals
// normal way, but with byte interval:
static uint32_t last4 = 0;
if (now - last4 >= (byte)interval ) {
Serial.print('b');
last4 += (byte)interval;
}
// normal way, but with uint interval:
static uint32_t last5 = 0;
if (now - last5 >= (uint16_t)interval ) {
Serial.print('i');
last5 += (uint16_t)interval;
}
// ## smaller size timestamps
// normal way, but with uint8_t:
// (never triggers with (uint8_t)interval==255)
static uint8_t last2 = 0;
if ((uint8_t)(now - last2) >= (uint8_t)interval ) {
Serial.print('B');
last2 += (uint8_t)interval;
}
// normal way, but with uint16_t:
static uint16_t last3 = 0;
if ((uint16_t)(now - last3) >= (uint16_t)interval ) {
Serial.print('W');
last3 += (uint16_t)interval;
}
earlyReturnFunction();
//delay(100);
}
// Early return way:
void earlyReturnFunction(void) {
static unsigned long lastER = -interval;
if (now - lastER < interval ) return;
Serial.print('E');
lastER += interval;
}