Repeated redundant gpio writes?

void loop {
  candleOn = deboucedbutton.read();
  if (candleOn) {
    analogWrite(candle_pin, random(0,1024));
  } else {
    analogWrite(candle_pin, 0);
  }
}

The code above spends most of its life in the else branch.
For maybe hours on end, my mcu will just be writing 0 to that analogue output.

I could put in a check like

else {
     if (buttonReleased) {
       //runs once
       analogWrite(candle_pin, 0);
     }
  }

I don’t really feel like writing some kind of state machine that keeps tracks of my button If I don’t have to. Do MCUs care If I write the same value to it over and over again, or do they have some internal check that ignores redundant instructions.

Hey @Pixmusix,

My guess is that the MCU won’t ignore that instruction and will keep analogWriting 0 out. However, I think all you will be doing is writing into a register the duty cycle value (of 0). This whole operation would only take up a handful of CPU cycles, so the impact is almost none. Unless your application cares about precision measured down to the microsecond, I think it will be fine.

To avoid continuously writing the analog output as 0, you could create a flag to indicate whether the button is currently pressed or not, and check that before writing. I think this might save you a few cycles? But the gain would be almost non-measurable.

Is there anything in particular the code is for?

1 Like

As long as I’m not damaging my MCU I really don’t mind about speed.
Thanks Jaryd.

It’s a flicker effect for a doll house fireplace.

2 Likes

Yeah no issues there, other factors would wear the MCU far more.

2 Likes