Can't get leading 0 to time format

Hi,

I'm experimenting with my RTC and although I came across lots of examples I can not get to work the preceding zeroes on the LCD neither Serial. I don't get any errors just doesn't add the zeroes if the number is < 10.

What I'm doing wrong???

#include <Time.h>
#include <Wire.h>
#include <DS1307RTC.h>
#include <LiquidCrystal.h>

LiquidCrystal lcd(8, 13, 9, 4, 5, 6, 7);

void setup () {
  
  lcd.begin (16,2);
  setSyncProvider (RTC.get);
  
}

void loop () {
  
  digitalClockDisplay();
  delay (1000);
  lcd.clear();
  
}

void digitalClockDisplay () {
  
  lcd.print (hour());
  lcd.print (":");
  lcd.print (minute());
  lcd.print (":");
  lcd.print (second());
  lcd.print (" ");
  
  
}

void printDigits(int digits){
  // utility function for digital clock display: prints preceding colon and leading 0
  lcd.print(":");
  if(digits < 10)
    lcd.print('0');
  lcd.print(digits);
}

When printing any number there are no leading 0's. When did you ever write 000001 and not just 1.

Mark

holmes4:
When printing any number there are no leading 0's. When did you ever write 000001 and not just 1.

Well with time, for a start, and that's what the OP's asking.

It's more usual to see....

07:05:08

rather than...

7:5:8

yes!

so try something like this untested code...

void digitalClockDisplay () 
{
  if (hour() < 10) lcd.print("0");
  lcd.print (hour());
  lcd.print (minute() < 10? ":0" : ":");
  lcd.print (minute());
  lcd.print (second() < 10? ":0" : ":");
  lcd.print (second());
  lcd.print (" ");
}
1 Like

BL it's waaaaay easier to use the print2digits (or printDigits as in that sketch) approach. Only requires that each call calls print2digits instead of just print, and no need to remember to code that ternary into every line where a time element is called.

void digitalClockDisplay () 
{
  char buffer [9]; 
  sprintf (buffer, "%02d:%02d:%02d", hour (), minute (), second ());
  lcd.print (buffer);
}

JimboZA:
BL it's waaaaay easier to use the print2digits (or printDigits as in that sketch) approach.

of course, you are correct... Just an example of a way to mash his code.

lots of ways to open a banana, I did it with a steamroller, i guess