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.