Snprintf and unsigned long issue

I wrote a sketch to track "uptime" of custom Arduino like board I made. Because I'm using watchdog sleep, millis() is not working so I had to come up with my own time tracking...
However for some reason it never prints "seconds" value, only minutes, hours and days. When I Serial.print (seconds) it works, but when I use it snprintf function it doesn't. I tried using both %02d, %02ld and %02lu, nothing works... I'm getting weird value of "2621" when seconds=40 for example...

#include "LowPower.h"

#define MULTIPLIER 5
unsigned long lastUpdate; //keep track of last time 
unsigned long lastMillis;

 int days;
 int hours;
  unsigned long minutes;
  unsigned long seconds;

void setup()  {
  Serial.begin(115200);
 
}

void loop() {
  printTime();
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
  lastMillis=(unsigned long)millis()-lastMillis;
  Serial.print ("lastMillis: "); Serial.println (lastMillis);
  lastUpdate=lastUpdate+8000UL*MULTIPLIER+lastMillis;
  Serial.print ("lastUpdate:"); Serial.println (lastUpdate);
  
}

void printTime() {
  char buffer[14];
  seconds = lastUpdate/1000;
  Serial.print ("Seconds: "); Serial.println (seconds);
  minutes=seconds/60;
  Serial.print ("Minutes: "); Serial.println (minutes);
  hours=minutes/60UL;
  days=hours/24;
  seconds=seconds-(minutes*60);
  minutes=minutes-(hours*60);
  hours=hours-(days*24);
  snprintf (buffer,sizeof(buffer),"%02d:%02d:%02d:%02ld",days,hours,minutes,seconds);
  Serial.println (buffer);
  delay (10);
  
}

If you can REALLY fit the value in 2 places, why do you need an unsigned long for seconds?

try a 'u' instead of a 'd'

And make buffer bigger.

Should help you spot the mistake...

snprintf (buffer,sizeof(buffer),"%02d:%02d:%02d:%02ld", int, int, unsigned long, unsigned long );

Oh thanks! That did it! :slight_smile:
snprintf (buffer,sizeof(buffer),"%02d:%02d:%02ld:%02ld", days,hours,minutes,seconds);

PaulS:
If you can REALLY fit the value in 2 places, why do you need an unsigned long for seconds?

Are you saying seconds don't need to be unsigned long? I thought so too but I can't figure out how "trim the fat" :slight_smile:

Are you saying seconds don't need to be unsigned long?

Let's say, for the sake of argument, that it does.

"%02d:%02d:%02ld:%02ld", days,hours,minutes,seconds

days, hours, minutes, and seconds will each be output using 2 characters. Now, how big a value can you define that uses only two characters? The values will range between 00 and xx. So, what size variable do you need to store a value between 00 and xx? What is xx? That depends on the base you are using, don't you think. What base ARE you using?

Now, the variable used for intermediate calculations and the variable used to hold the value being output don't HAVE to be the same variable, do they?