For some time I've been using the 'reset' code recommended in Robin2's excellent tutorial here:
https://forum.arduino.cc/t/demonstration-code-for-several-things-at-the-same-time/217158
Instead of the familiar and widely used
previousMillis = currentMillis;
I use
previousMillis += interval;
I'd assumed that it was universal, but a current sketch I'm writing seems to prove otherwise. It works with the familiar method but causes triggering well before the set interval with the alternative.
The simple example below does the same. It arises when I set a non-zero value for previousMillis, (which I occasionally do when testing, to shorten an otherwise long delay before the first activation).
But I can't fathom the reason?
unsigned long currentMillis;
unsigned long previousMillis;
const unsigned long interval = 5000;
void setup()
{
// Start serial communication for debugging purposes
Serial.begin(115200);
// delay(200);
Serial.println("Robin2Puzzle");
Serial.println("========================================");
Serial.println("Setup ended, millis = ");
Serial.println(millis());
previousMillis = 2; // Reset fails if this is 2 or more.
// But the familiar method works regardless
}
void loop()
{
currentMillis = millis();
if (currentMillis - previousMillis >= interval)
{
Serial.println("Interval has ended");
previousMillis += interval; // Reset; fails if line 20 set to
// a value of 2 or more. Not clear why?
// previousMillis = currentMillis; // Reset; always works
}
}