Why does this code lead to Arduino Mega2560 constantly resetting?
void setup() {
Serial.begin(9600);
Serial.println("SETUP");
delay(500); //without this line Serial prints "SESESESESE"
analogWrite(10, 100);
analogWrite(11, 50); //reboots after this line
}
void loop() {
Serial.println("LOOP"); //doesn't reach here
}
Arduino serial outputs the following:
SETUP
SETUP
SETUP
SETUP
SETUP
SETUP
SETUP
SETUP
Things to note:
1) Arduino does not reboot if I substitute pins 10 and 11 with some others (8 and 9 for example), but it does also reboot with pins 12 and 13 (I guess pins 10-13 are somehow special).
2) Arduino does not reboot if I use equal values in the calls to analogWrite
(100 and 100 for example).
Apparently, the compiler's optimizations are to blame. After adding these two lines at the start of the program it finally works as it should:
void setup() __attribute__((optimize("-O1")));
void loop() __attribute__((optimize("-O1")));