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);
    }
}
1
  • legThreeBrightness = 255 doesn't do what you think it does. Turn up your compiler warnings and pay attention to what it says. Aug 9, 2020 at 18:51

1 Answer 1

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.

5
  • 2
    sigh... that was it. I completely forgot that its a double == for comparison.
    – Keltari
    Aug 9, 2020 at 2: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 9, 2020 at 11:03
  • 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
    Aug 9, 2020 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 9, 2020 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.