Hello, I need some advice on how to program timers. My goal is to create a timer that will time how long my mcu has been on. Currently the code I have written so far saves the number of minutes my board has turned on for into the EEPROM. Instead of counting hours I count minutes for the time being to help speed my process up and it works great. I am just concerned that being dependent on a millis call will show some inaccurate counting as my program gets larger in functionality.
My code is below. It counts the seconds and every time it hits 60 seconds I save a +1 into the EEPROM which is minutes. If I turned this into saving hours, I would count the minutes and save a +1 into the EEPROM.
#include <Arduino.h>
#include <EEPROM.h>
#include <TimeLib.h>
#include <Streaming.h>
// Address in EEPROM to store the total uptime
#define UPTIME_ADDRESS 0
unsigned long startTime;;
unsigned long readTotalUptime;
struct {
int operationalHours = 0;
elapsedMillis checkTime = 0;
} OOH;
void setup() {
Serial.begin(9600);
while (!Serial) {
;
}
startTime = millis(); // Record the starting time
//Serial << "StartUp OOH read: " << EEPROM.read(UPTIME_ADDRESS) << endl;
}
void loop() {
if (OOH.checkTime >= 1000) {
OOH.checkTime = 0;
unsigned long currentTime = millis();
unsigned long uptime = currentTime - startTime;
if (EEPROM.read(UPTIME_ADDRESS) >= 5) {
Serial << "You are OUT of time!" << endl;
for ( unsigned int i = 0 ; i < EEPROM.length() ; i++ )
EEPROM.write(i, 0);
}
else {
// Calculate hours, minutes, and seconds from uptime
unsigned long Hours = uptime / 3600000;
unsigned long Minutes = (uptime / 60000) % 60;
unsigned long Seconds = (uptime / 1000) % 60;
Serial << Seconds << endl;
// Save the updated total uptime to EEPROM
if (Seconds == 59) {
OOH.operationalHours++;
EEPROM.write(UPTIME_ADDRESS, OOH.operationalHours);
}
}
Serial << "OOH: " << EEPROM.read(UPTIME_ADDRESS) << endl;
}
}