Hey guys,
Does anybody encountered a problem, when Arduino computed weird numbers? When i run this simple sketch i get these computations on serial monitor.
void setup() {
Serial.begin(9600);
}
void loop() {
unsigned long sec;
long sec2;
sec=10*3600;
sec2=10*3600;
Serial.println(sec);
Serial.println(sec2);
}
The default int size is 16 bit, all intermediate calculations use 16 bit unless forced otherwise by declaring
long constants. 10 * 3600 doesn't fit in a signed 16 bit int.
Set your 'Compiler warnings' preference to "All". That would have pointed you directly to your mistakes:
/Users/john/Documents/Arduino/sketch_dec10a/sketch_dec10a.ino: In function 'void loop()':
/Users/john/Documents/Arduino/sketch_dec10a/sketch_dec10a.ino:9:12: warning: integer overflow in expression [-Woverflow]
sec = 10 * 3600;
^
/Users/john/Documents/Arduino/sketch_dec10a/sketch_dec10a.ino:10:13: warning: integer overflow in expression [-Woverflow]
sec2 = 10 * 3600;
^
Sketch uses 2042 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 188 bytes (2%) of dynamic memory, leaving 8004 bytes for local variables. Maximum is 8192 bytes.