arithmetic problems

Hey,

As part of a larger project I set up a basic timeout in a while loop but I ran into a strange problem in the process and I was hoping someone could shed some light on this.

void setup() {
  Serial.begin(9600);
  unsigned long timeout = millis() + (1000 * 60 * 15); // fifteen minutes
  Serial.println(timeout);
}

void loop() {
}

This example sketch shows how I was trying to declare my timeout variable. I would expect this to print something close to 900000 but it prints 4294949792

If I do timeout = millis() + (10 * 10 * 10)
I get 1000 like I would expect

What's going on here?

Thank you

What's going on here?

By default, an integer constant is treated as an int with the attendant limitations in values. To specify an integer constant with another data type, follow it with:
a 'u' or 'U' to force the constant into an unsigned data format. Example: 33u
a 'l' or 'L' to force the constant into a long data format. Example: 100000L
a 'ul' or 'UL' to force the constant into an unsigned long constant. Example: 32767ul

unsigned long timeout = millis() + (1000UL * 60 * 15); // fifteen minutes

See: Gammon Forum : Electronics : Microprocessors : Integer arithmetic and overflow

Thank you very much!!

900,000 = 0xDBBA0 but gets truncated to 0xBBA0 when you use 16-bit math.

When you add the int 0xBBA0 to an unsigned long it gets sign-extended to 32-bits: 0xFFFFBBA0

When you treat 0xFFFFBBA0 as an unsigned long the value is 4,294,949,792.