How do I use millis() to display a real time clock? Just a simple hh:mm:ss:ms time display. ms is the milliseconds for every second. If it works without millis then thats fine too!
Thank you very much! Just quickly millis() gives me a four digit number that is updating with the left most number being the number of seconds. Do you know how I can get the number that is second from the left only? For example, if the current time is 2345, I just want to get the number 3. Many thanks!
Do you know how to split a number with no spaces? For example the number 1234, how would I get the 2? the function split() wont work because it separates a list of numbers with spaces. Many thanks
If your intent is to have a real-time clock, the recommendation to use the Time & Date functions from the reference is the easiest option. If you want to display a digital clock accurate to the millisecond, the modulo and division operators are your best friends. This method for a stopwatch app I made takes in milliseconds as an input and returns a String as an output, with the String being formatted hh:mm:ss:ms
String timeFormat(int millis) {
String t = "";
int hours = millis / 3600000;
//there are 3600000 milliseconds in 1 hour, so integer division will produce the number of hours
int minutes = (millis % 3600000) / 60000;
//there are 60000 milliseconds in 1 minute, but it will not suffice to simply divide, as the number of hours needs to be disregarded when counting minutes.
//This is done through the modulo operator (%). Modulo returns the remainder of a division operation.
//Without the modulo, when the minutes pass 59, the minute will count 60, 61, etc.
//But, with the modulo, when minutes pass 59, the number of milliseconds used to calculate minutes resets to zero, which is the intended behavior of the clock.
int seconds = (millis % 60000) / 1000;
//The same logic is applied to seconds and milliseconds.
int milliseconds = millis % 1000;
//The rest is just string formatting
t += hours + ":";
if (minutes < 10) {
t += "0";
}
t += minutes + ":";
if (seconds < 10) {
t += "0";
}
t += seconds + ".";
if (milliseconds < 10) {
t += "00";
} else if (milliseconds < 100) {
t += "0";
}
t += milliseconds;
return t;
}
If you want to use this function, you’ll have to look elsewhere to find how to get a real-time millisecond count, and you may have to adjust the method to take a long as an input instead of an integer.