I am trying to count seconds minutes and hours and accumulate an analogue value, (measuring Ampere Hours), averaging the current reading and recording the time taken. If I could reset mills() I could ‘increment the minutes’ and reset the seconds, but I can’t find a way to reset millis() which is of course where the seconds were derived.
Is there a way, or do I need to use an RTC.
You don't need to reset millis, you just need to keep track of what it was last time in a variable and subtract from the current time to figure out how long it has been.
Andy207:
I am trying to count seconds minutes and hours and accumulate an analogue value, (measuring Ampere Hours), averaging the current reading and recording the time taken. If I could reset mills() I could ‘increment the minutes’ and reset the seconds, but I can’t find a way to reset millis() which is of course where the seconds were derived.
Is there a way, or do I need to use an RTC.
Many thanks, Andy
One way is to read millis() at the beginning of the time you want to measure, and again at the end, and then subtract to get the measurement in milliseconds. If you want hours, minutes, and seconds, then you can use arithmetic. Since there are 3,600,000 milliseconds in 1 hour, you can divide the number of milliseconds by 3,600,000 to get the number of hours.
// before anything else, you will need to declare some variables
unsigned long startMillis;
unsigned long endMillis;
// do this at the beginning of the time you want to measure
startMillis = millis();
// do this at the end of the time you want to measure
stopMillis = millis();
// do this to calculate the hours, minutes, and seconds
unsigned long totalTime = stopMillis - startMillis;
unsigned long leftover = totalTime;
int hours = leftover / 3600000UL;
leftover %= 3600000UL;
int minutes = leftover / 60000UL;
leftover %= 60000UL;
int seconds = leftover / 1000UL;
leftover %= 1000UL;
int thousandths = leftover;
// after the calculations, do this to output the result
Serial.print("Elapsed time: ");
Serial.print(totalTime);
Serial.println(" ms");
Serial.print("that is ");
Serial.print(hours);
Serial.print(" h ");
Serial.print(minutes);
Serial.print(" min ");
Serial.print(seconds);
if (thousandths < 10) {
Serial.print(".00");
}
else if (thousandths < 100) {
Serial.print(".0");
}
else {
Serial.print(".");
}
Serial.print(thousandths);
Serial.println(" s");
Andy207:
I am trying to count seconds minutes and hours and accumulate an analogue value, (measuring Ampere Hours), averaging the current reading and recording the time taken. If I could reset mills() I could 'increment the minutes' and reset the seconds, but I can't find a way to reset millis() which is of course where the seconds were derived.
Is there a way, or do I need to use an RTC.
Many thanks, Andy
Do you need to reset your clock every time you look at it, to see how much time has passed?