LED PWM with Tact switch

While the button is pressed, led is fade on gradually. Using pwm when the Brightness value is more than 255, the value is reset to 0 while the button is not pressed, the Brightness keeps brightest value.

This is my Task.

so I write my code like this

#define buttonPin 2
#define ledPin 6

int buttonState = 0;
int brightness = 0;
int fadeAmount = 5;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  brightness = 255;
  analogWrite(ledPin, brightness);
  if (buttonState == 1) {
    fadeAmount = 5;
    brightness = 0;
    while(brightness <= 255){
      brightness = brightness + fadeAmount;
      analogWrite(ledPin, brightness);
      delay(80); 
      if(buttonState == 0){
        fadeAmount = 0;
        brightness = 255;
        break;
      }
    }  
  }
}

But this code has a error.
When I release my hand from the tact switch, it should continue to be lit at full brightness at LED. However, it seems that the loop when the tact switch is pressed is executed once, resulting in a single flicker.

Hello adong0808

Welcome to the worldbest Arduino forum ever.

It seem to be a school asignment, isn´t it?

There's a trick to figuring out why something isn't working:

Use a logic analyzer to see what happens.
Put Serial.print statements at various places in the code to see the values of variables and determine whether they meet your expectations.

1 Like

buttonState does not magically follow the state of the button. You must digitalRead() the button if you are looking for an update to the current pressed or not pressed changes to the button.

a7