Disturbing math problem with Arduino. Overflow?

Hi!

I've stumbled upon a problem that i just cant figure out the cause of.
This little code snippet from a test program pretty much sums up what I'm having a hard time figuring out:

long b = 255000;
Serial.println(b);
long a = 1000*255; // 1000 * 255 = 255000 //
Serial.println(a);
delay(1000);

The serial output of 'b' is: 255000
while the serial output for 'a' is: -7144

Could anyone please explain to me why this happens?
I first stumbled upon this when i tried to use a map function. When it always returned '0' i started looking into it and the above is where i couldn't get any further on my own.

Thanks!

-Rindis

What does :

long a = 1000L*255L;

give?

Hm, that solved it. Whats up with the L? Never seen that before.

-Rindis

Aha, so see if i got this right. With the L you force the numbers into long integers and that keeps them from overflowing?

-Rindis

Correct.
You could probably get away with "1000L * 255;"

Okey thanks! Learned something new today as well :slight_smile:

Tried the map function now again, that still returns 0 tho.

yOut = map(yOut, 0L, 1023L, 0L, 255L);

When i print out the value of 'yOut before the map it prints the value '1000', when i print it out after the map function it shows '0'.
If i replace 'yOut in the map function with the integer '1000' the map function returns '250'.
The variable yOut is a long int btw.

Using:

yOut = (yOut * 255L) / (1023L);

causes the same problem. Thoughts?

Thanks!

-Rindis

Okey, i figured out the problem! And i have now made my own functioning PID-regulator! Yay! :smiley: