// https://wokwi.com/projects/387510129380013057
// code for creating a "seconds" variable from millis()
// that won't roll over for 136 years
// https://forum.arduino.cc/t/using-seconds-instead-of-millis-for-136-year-rollover/1213864
const long SecondsInDay = 3600L * 24;
const long SecondsInYear = SecondsInDay * 365;
// time variables to track elapsed seconds for
// 2^32/3600/24/365=136 years before secondsrollover
unsigned long seconds = 0, lastSecondMs = 0;
unsigned long currentMillis = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
}
void loop() {
if (timeStuff()) { // 1ms tick, UI stuff
report();
blinkLedQuarterly();
}
}
bool timeStuff(void) { // maintain seconds variable and check for ms tick
bool retval = false;
const unsigned int interval = 1;
static unsigned long last = 0;
currentMillis = millis();
if (currentMillis - last >= interval) {
retval = true;
last += interval;
if (currentMillis - lastSecondMs >= 1000) {
++seconds;
lastSecondMs += 1000;
}
}
return retval;
}
void report(void) {
const unsigned long interval = 500;
static unsigned long last = 0;
if (currentMillis - last >= interval) {
last += interval;
Serial.print("ms:");
Serial.print(currentMillis);
Serial.print(" Sec:");
Serial.print(seconds);
Serial.print(" min:");
Serial.print(seconds / 60);
Serial.println();
};
}
void blinkLedQuarterly(void) {
static unsigned long last = 0;
unsigned long interval = SecondsInYear / 4;
if (seconds - last >= interval) {
last = seconds;
digitalWrite(LED_BUILTIN, digitalRead(LED_BUILTIN) == HIGH ? LOW : HIGH);
}
}