I am new with Arduino, but I have been programming embedded systems more than 10 years.
Is there some limits with Arduino compiler? On my first project I found that compiler doesn't work as it should, here is a simplified sample code:
// led blink speed in ms
#define LED_BLINK_SPEED 1000
void setup()
{
Serial.begin(9600);
}
void loop()
{
unsigned long ledspeed = LED_BLINK_SPEED * 1000;
Serial.println(ledspeed);
delay(1500);
}
Problem is with "unsigned long ledspeed = LED_BLINK_SPEED * 1000;" line.
ledspeed should be one million (1000000), but it will be 16960. It seems that it's using 16bit variable where that multiply result is stored before it's moved to that 32 bit variable.
Fix is simple "unsigned long ledspeed = (unsigned long) LED_BLINK_SPEED * 1000;", but now I am asking why Arduino doesn't use 32bit result store without casting? ARM processor compiler works without casting, or is this issue with some compiler flags?
The default for a numeric literal is an int, and you are multiplying two together. The result you get is consistent with the way an int would be truncated, and then the result is placed in an unsigned long.
I suggest:
const unsigned long LED_BLINK_SPEED = 1000;
That should fix it. Better to use consts rather than defines anyway.
jaahaavi:
Fix is simple "unsigned long ledspeed = (unsigned long) LED_BLINK_SPEED * 1000;", but now I am asking why Arduino doesn't use 32bit result store without casting? ARM processor compiler works without casting, or is this issue with some compiler flags?
It's g++, not the "Arduino compiler" as such. Maybe the ARM defaults to 32 bit ints, quite a few processors do.
With older x86 PCs and smaller processors (8- and 16-bit) sizeof int is 2. On later PCs (Pentium) and other processors (PowerPC, ARM, etc.) sizeof int is 4.