I’m working on a project that has an intermittent pump, and I want to keep a running total of the time that the motor is on in a 24 hr period. I could do this with millis() and store past values to keep a running total, but wondered if there are any clever ways of doing this with the Blynk timer widgets or RTC. There is no code yet, as this is at the concept stage only. Any ideas are greatly appreciated.
Better use NTP library ( or Real-time clock RTC Widget ) as well as TimeLib library to keep tracks with real date stamp, something like this:
char currentDateTime[22];
sprintf(currentDateTime, "%02d/%02d/%d %02d:%02d:%02d",day(), month(), year(), hour(), minute(), second());
Blynk.virtualWrite(V5, currentDateTime); /// V5 could be a Value Display, or Terminal etc
Cheers
There is actually an issue with using the millis function that most people overlook…
millis() starts as zero when your MCU boots then increments by 1 every millisecond that the MCU is running.
However, as the millis value is stored as an unsigned long variable, the maximum value that can be stored is 4,294,967,295
This equates to around 49 days, so at some point on day 49 your millis counter will reset to zero.
If you’re using code that captures the millis value at the start of a process then checks to see if the current millis value is greater than your captured value plus x number of additional millis before stopping the process then it will work fine until you happen to capture the current millis value just before it jumps back to zero.
Your test in the code to see if the current millis value is greater than the captured value won’t then be true for another 49 days - or possibly never true.
If you captured a millis value of 4,294,967,000 and we’re testing for that value plus 1000, it’s impossible to ever reach that situation as the counter would reset to zero after another 295 millis.
In a non critical situation that may not matter, you’d simply think your MCU had locked-up and reboot it, but if the MCU is controlling your home heating system for example it may prove to be much more annoying or expensive.
Pete.
Sprintf seems to be memory hungry. The code occupies 4 to 5% more of sketch memory depending on the type of board. We can save that precious space, if needed to, by concatenating the datetime into a String as:
String tm = "";
tm += day();
tm += "/";
tm += month();
tm += "/";
tm += year();
tm += " ";
tm += hour();
tm += ":";
if (minute() < 10) {
tm += "0";
tm += minute();
}
else tm += minute();
tm += ":";
if (second() < 10) {
tm += "0";
tm += second();
}
else tm += second();
Blynk.virtualWrite(V5, tm); /// V5 could be a Value Display, or Terminal etc