Menu
CoddyTech

Times in unsigned long

Part of the Timing Without Delay section of Coddy's Arduino journey. Lesson 2 of 18.

A variable can only hold numbers up to a size, set by its type. An int on the Uno holds -32768 to 32767. After 32.8 seconds, millis() is bigger than that, and an int that tries to hold it wraps around to a negative number.

An unsigned type has no negative numbers, so it reaches twice as high: an unsigned int holds 0 to 65535, about 65 seconds of milliseconds. Still not enough.

An unsigned long holds 0 to 4,294,967,295. In milliseconds that is more than 49 days, and it is the type millis() itself returns. Store every time in one:

unsigned long now = millis();
unsigned long startTime = 0;

A sketch with the wrong type works for half a minute and then goes wrong, so the bug is easy to miss.

challenge icon

Challenge

Easy

This sketch prints the time once a second, but after 32 seconds it prints negative numbers. Change the type of now so the time stays right for days.

Press Run and wait past 33 seconds to see the bug, then fix it and Check.

Try it yourself

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

void loop() {
  int now = millis();   // this type is too small for the time: change it
  Serial.println(now);
  delay(1000);
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Timing Without Delay

Practice on your own: Arduino playground