3

I am trying to do something very simple. I want the LED to fade from full brightness to off. This works... However, the LED turns back on to full brightness and fades again, in a loop. I am not sure why. I think I am missing something obvious. Once the legThreeBrightness decrements to 0, nothing should happen...

int legThreeBrightness = 255;

void setup() {

    pinMode(3, OUTPUT);

}  

void loop() {  
  
    if (legThreeBrightness = 255){
        do {
              analogWrite(3, legThreeBrightness);
              delay(30);
              legThreeBrightness = legThreeBrightness -5;
           } while (legThreeBrightness >= 0);
    }
}
Keltari
  • 163
  • 6
  • `legThreeBrightness = 255` doesn't do what you think it does. Turn up your compiler warnings and pay attention to what it says. – Mooing Duck Aug 09 '20 at 18:51

1 Answers1

9

This line:

if (legThreeBrightness = 255){

assigns the value 255 to legThreeBrightness. That is non-zero so it enters the block and runs the fade now that the variable has been set to 255.

If you just want to compare the value to 255 then use:

if (legThreeBrightness == 255){

and that way when the loop function repeats it isn't there setting the value back to 255. This way it will stay at 0.

Delta_G
  • 2,628
  • 2
  • 9
  • 21
  • 2
    sigh... that was it. I completely forgot that its a double == for comparison. – Keltari Aug 09 '20 at 02:43
  • 2
    @Keltari Rookie mistake, we've all made it. Make sure you keep an eye on your operators whenever you're debugging :-) – Mast Aug 09 '20 at 11:03
  • https://en.m.wikipedia.org/wiki/Yoda_conditions – Filip Franik Aug 09 '20 at 13:32
  • 2
    There are also some compilers that will warn you about this. If you count up the time you spent debugging this, it might be a better use to figure out if/how your compiler can. – JonathanZ supports MonicaC Aug 09 '20 at 13:55
  • 1
    @Keltari if you'd like, you can follow @JonathanZsupportsMonicaC's suggestion to enable compiler warnings. Go to File -> Preferences -> Compiler warnings: and set it to `More`. If you'd like the compilation to fail instead of just issuing a warning, add `#pragma GCC diagnostic error "-Wparentheses"` to the top of your program. – lights0123 Aug 09 '20 at 18:02