I'm using Windows 10, Arduino 1.8.12 (Windows Store 1.8.33.0)
I have an Arduino MEGA 2560 and a red LED connected to pin 4.
#define RED 4
#define GREEN 2
void setup() {
analogWrite(GREEN, 0);
analogWrite(RED, 100);
}
void loop() {
}
This code lights up the red LED.
However, when I write 1 to the GREEN pin
analogWrite(GREEN, 1)
, the red LED goes off. I'm expecting the red LED to stay on.
#define RED 4
#define GREEN 2
void setup() {
analogWrite(GREEN, 1);
analogWrite(RED, 100);
}
void loop() {
}
The red LED stays on when both written values are the same, e.g.
analogWrite(GREEN, 25);
analogWrite(RED, 25);
I also found that adding some "garbage" code at the beginning fixes the issue. I wasn't able to get the garbage into a simpler form without both pins shutting off.
#define RED 4
#define GREEN 2
void setup() {
// GARBAGE BEGIN ===
unsigned long t = millis();
const unsigned long period = 10;
float progress = float(t % period)/period;
float r = progress * 0;
// GARBAGE END ===
analogWrite(GREEN, 100 + r);
analogWrite(RED, 50 + r);
}
void loop() {
}
Update: Thanks all for your comments. Setting the pinMode to output did not fix the issue. However, changing the function declaration to __attribute__((optimize("-O0"))) void setup() {
fixed the issue. -O1
also works, but -O2
fails.