Text & Time Formatting
Build fixed-width text with snprintf: times, dates and a live clock on the LCD, and floats with dtostrf because the Uno cannot print %f.
Formatted text with snprintf
snprintf(buffer, sizeof(buffer), format, values...) writes text into a char array, following a format like "%02d:%02d". %d is an int, %02d pads it to two digits with a leading zero, and %s is text. Lesson 26 uses it to format clock times.
On the Uno %f does not work - it prints ?. Use dtostrf() to turn a float into text first.
formatMinutes()
Write formatMinutes so it returns a time in seconds as MM:SS text - 125 seconds becomes 02:05. Use snprintf with %02d into the char array, then return String(buffer).
02:05
formatTime()
Now the full clock: write formatTime so it returns the time as HH:MM:SS - 3725 seconds becomes 01:02:05. Same idea as the last exercise, with hours added.
01:02:05
formatDate()
An RTC gives the day, month and year as separate numbers. Write formatDate so it returns them as DD/MM/YYYY - day 5, month 9, year 2026 becomes 05/09/2026.
05/09/2026
Fixed-width text on the display
An LCD row is 16 characters and nothing clears itself. Build the whole field in a buffer first, with %02d padding so 9 becomes 09. Every update then writes the same number of characters in the same place, so no digits are left behind and the text never jumps sideways.
A clock on the display
Show the time since the board started as MM:SS on the top line, updating as it runs. Build the text with snprintf into a char buffer, as in the exercises above, then print the buffer.
millis() / 1000 is the number of whole seconds.
Why does it print a question mark?
formatVolts should return text like 4.73 V, but on an Uno it returns ? V, because the Uno's snprintf cannot handle %f. Fix it so the voltage appears with two decimals. dtostrf(value, 1, 2, text) writes a float into a char array; print that with %s.
4.73 V
Try it on a real Uno
Upload A clock on the display with the I2C LCD wired to A4 and A5. Then add the DS1307 RTC from Lesson 26 to the same two bus pins, and replace millis() / 1000 with the RTC's hour, minute and second - the snprintf line carries straight over.