millis() timer code not working?

Hi all!

So I have a timer set up in my code using the SimpleTimer library that I want to run for a month non-stop.

It seems to get stuck at 0:09:06:07 and then cycles to 0:0-9:0-6:0-8 and starts increasing from there.

Is there any way I can work around this and get it to count up to (theoretically) infinity? Code is found below. Thanks!

#include <SimpleTimer.h>

SimpleTimer timer;

void digitalClockDisplay() {
  int d,h,m,s;
  s = millis()/1000;
  m = s / 60;
  h = s / 3600;
  d = s / 86400;
  s = s - m * 60;
  m = m - h * 60;
  h = h - d * 24;
  Serial.print(d);
  printDigits(h);
  printDigits(m);
  printDigits(s);
  Serial.println();
}

void printDigits(int digits) {
  Serial.print(":");
  if(digits < 10) {
    Serial.print('0');
  }
  Serial.print(digits);
}

void setup() {
  Serial.begin(9600);

  Serial.println("Day:Hour:Minute:Second");
  Serial.println("0:00:00:00");
  timer.setInterval(1000, digitalClockDisplay);
}

void loop() {
  timer.run();
}

I'm going to guess your seconds are overflowing your 16-bit integer. (Maybe minutes will eventually overflow too.)

Try changing those variables to type unsigned long.

Yes, s = millis()/1000
s should be 'unsigned long'

Maybe you should be using an RTC.
DS3231

.

@LarryD @DVDdoug Thanks you guys! I'll try that out and see how it goes.

The integer 's' can hold up to 32767 seconds before overflowing and turning negative.

That is 9 hours 6 minutes and 7 seconds which is exactly when your display goes bad. :slight_smile: