I thought I would throw this out there. I was struggling trying to find a way to convert millis() into a more readable format but was having a hard time finding anything simple so I came up with this quick and dirty sketch that can be used as a function to convert milliseconds to HH:MM:SS
void setup() {
// This program converts a time in milliseconds, tme, to a string formatted as HH:MM:SS.
Serial.begin(9600);
}
void loop() {
int tme = 6473; //Time we are converting. This can be passed from another function.
int hr = tme/3600; //Number of seconds in an hour
int mins = (tme-hr*3600)/60; //Remove the number of hours and calculate the minutes.
int sec = tme-hr*3600-mins*60; //Remove the number of hours and minutes, leaving only seconds.
String hrMinSec = (String(hr) + ":" + String(mins) + ":" + String(sec)); //Converts to HH:MM:SS string. This can be returned to the calling function.
Serial.print("String Time: ");Serial.println (hrMinSec);
while(1);
}
That's not using millis() at all. You are treating the 'tme' value as seconds, not milliseconds.
Perhaps you wanted:
unsigned long currentMillis = millis();
unsigned long seconds = currentMillis / 1000;
unsigned long minutes = seconds / 60;
unsigned long hours = minutes / 60;
unsigned long days = hours / 24;
currentMillis %= 1000;
seconds %= 60;
minutes %= 60;
hours %= 24;
6 Likes
The variable tme can be changed to millis() or whatever number/variable you want it to be.
Scottawildcat:
The variable tme can be changed to millis() or whatever number/variable you want it to be.
But millis() returns unsigned long, not int.
TheMemberFormerlyKnownAsAWOL:
But millis() returns unsigned long, not int.
And it also returns milliseconds and not seconds so the times would be off by a factor of 1000.
And it is very inefficient to use the String object just to convert numbers to characters.
And your minute and second fields aren't padded with leading 0's.
Serial.print(days);
Serial.print(' ');
Serial.print(hours);
Serial.print(':');
if (minutes < 10)
Serial.print('0');
Serial.print(minutes);
Serial.print(':');
if (seconds < 10)
Serial.print('0');
Serial.print(seconds);
Serial.print('.');
if (currentMillis < 100)
Serial.print('0');
if (currentMillis < 10)
Serial.print('0');
Serial.print(currentMillis));
2 Likes
This is for use in general terms. I didn't need 10ths , 100ths or milliseconds, just seconds. Plus, by putting it into a string, it can be returned and used for other things besides just printing on the screen.