millis() rollover safe code

The following code is an example to switch on an output for a Runtime, then off for an interval. Written for Arduino IDE.
This code takes into account the issues with millis() rollover, which disallows comparing two distinct times in a loop, as discussed elsewhere.

unsigned long startTime = 0;      // Initialize to 0
unsigned long stopTime = 0;
unsigned long interval = 10000;
unsigned long RunInterval = 5000;
bool output = false;

void setup() {
  Serial.begin(115200);
  while (!Serial) delay(50);
  Serial.println("POTATO");
  startTime = millis();          // Set the start time during setup
}

void loop() {
  unsigned long currentTime = millis(); // Store the current time

  if (!output && currentTime - startTime >= interval) {
    Serial.println("OUTPUT SWITCHED ON");
    stopTime = currentTime;
    output = true;
  }

  if (output && currentTime - stopTime >= RunInterval) {
    Serial.println("OUTPUT SWITCHED OFF");
    startTime = currentTime;     // Update the start time for the next run
    output = false;
  }

  delay(1000);
  Serial.print("output = ");
  Serial.print(output);
  Serial.print(", Millis = ");
  Serial.println(currentTime);
}
Scroll to Top