简体   繁体   中英

Arduino Mega2560 reboots after two consecutive calls to analogWrite

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).

This behavior should not happen, if you set your pins to:

 void setup() {
    pinMode(10, OUTPUT);  // sets the pin as output
    pinMode(11, OUTPUT);  // sets the pin as output

Such resets are typical of a bad power supply, noise or bad connections, (bad protoboard), or a bad LED pin (eg; resistor too small or damaged, or damaged pin, etc). If your mega has no HW-defect and a sufficient power source or additional HW attached that causes this defect, it should work as expected.

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")));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM