NTP Client tutorial code simplification

Hello,

In the Ntp Client tutorial, the example code convert an UNIX time stamp to be sent as HH:MM:SS to Serial :

// print Unix time:
Serial.println(epoch);
// print the hour, minute and second:
Serial.print("The UTC time is ");       // UTC is the time at Greenwich Meridian (GMT)
Serial.print((epoch  % 86400L) / 3600); // print the hour (86400 equals secs per day)
Serial.print(':');
if (((epoch % 3600) / 60) < 10) {
    // In the first 10 minutes of each hour, we'll want a leading '0'
    Serial.print('0');
}
Serial.print((epoch  % 3600) / 60); // print the minute (3600 equals secs per minute)
Serial.print(':');
if ((epoch % 60) < 10) {
    // In the first 10 seconds of each minute, we'll want a leading '0'
    Serial.print('0');
}
Serial.println(epoch % 60); // print the second

It could be simplified by the use of sprintf() function :

byte h=0,m=0,s=0;
char heure[9];
// print Unix time:
Serial.println(epoch);
// print the hour, minute and second:
Serial.print("The UTC time is ");       // UTC is the time at Greenwich Meridian (GMT)
h = (epoch % 86400L) / 3600;
m = (epoch  % 3600) / 60;
s = epoch % 60;		
sprintf(heure,"%02d:%02d:%02d",h,m,s);
Serial.println(heure);

Regards

Pierre

Compiling the tutorial code for Uno:

Sketch uses 11436 bytes (35%) of program storage space. Maximum is 32256 bytes.
Global variables use 650 bytes (31%) of dynamic memory, leaving 1398 bytes for local variables. Maximum is 2048 bytes.

Compiling your code for Uno:

Sketch uses 12870 bytes (39%) of program storage space. Maximum is 32256 bytes.
Global variables use 666 bytes (32%) of dynamic memory, leaving 1382 bytes for local variables. Maximum is 2048 bytes.

Good to know. I missed this increase of memory needed. I suppose it's the binaries of sprintf().
By the way, If you want to use less Serial.print calls and no more memory, you could directly populate the string :

char heure[]="00:00:00";
byte h=0,m=0,s=0;
// print Unix time:
Serial.println(epoch);
// print the hour, minute and second:
Serial.print("The UTC time is ");       // UTC is the time at Greenwich Meridian (GMT)
h = (epoch % 86400L) / 3600;
m = (epoch  % 3600) / 60;
s = epoch % 60;		
heure[0]=h/10+48;
heure[1]=h%10+48;
heure[3]=m/10+48;
heure[4]=m%10+48;
heure[6]=s/10+48;
heure[7]=s%10+48;
Serial.println(heure);

The sketch uses now only 11326 bytes, but the source code is less clear.

but the source code is less clear.

It would be clearer with some spaces and with '0' instead of 48.