Quick fading-out-led question

Hi, everyone. I am really to Arduino. I'd like to quicklly ask about the fading out led.
The fading in is working now. And I would like my led fading out when button pressed. Really apprieciate any help!

Here is my code:

int led = 9; 
int button = 2;

int brightness = 0;    
int fadeAmount = 5;    

void setup() {
   pinMode(button, INPUT_PULLUP);
   pinMode(led, OUTPUT);
 } 
 
 void loop() {
   analogWrite(led, brightness);
   brightness = brightness + fadeAmount;
   brightness = constrain(brightness, 0, 200);      //constrain the maximum brightness
 
   if (button == LOW){
   brightness = brightness - fadeAmount;
   }
   
   delay(100);
}

Hello lilyyyw
Check out the modified sketch.

int led = 9;
int button = 2;

int brightness = 0;
int fadeAmount = 5;

void setup() {
  pinMode(button, INPUT_PULLUP);
  pinMode(led, OUTPUT);
}

void loop() {
  // read current state of button and make either a
  if (digitalRead(button)) {
    // decrement
    brightness = brightness - fadeAmount;
  }
  else {
    //  or increment
    brightness = brightness + fadeAmount;
  }
  // limit value
  brightness = constrain(brightness, 0, 200);      //constrain the maximum brightness
  // write value
  analogWrite(led, brightness);
  // and wait for next round
  delay(100);
}

Have a nice day and enjoy coding in C++.
Дайте миру шанс!

1 Like

The sketch fixed by paulpaulson in Wokwi:

The human eye sees brightness with a steep curve, close to a 10log curve. If the sketch would use such a steep curve, then the dimming will look more natural.

1 Like

Here's a library to do the fading for you:

It's available in the IDE libraries.

1 Like

Follow the logic in your loop(). You increment the brightness with brightness = brightness + fadeAmount and if the button is pressed you decrement it with brightness = brightness - fadeAmount. The end result is that there is no change in the brightness when the button is pressed.

1 Like

Thanks for reaching out! Really appreciate your help.

Thanks for your help! I will have a look at it.

Thank you so much. This is helpful:)

Thanks for your suggestion. I will try to modify my code later :smiley:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.