arduinoarduino-idearduino-c++pwm

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.


Solution

  • I think the issue you're experiencing is because the buttonState variable is only being checked once at the beginning of each loop iteration. Once you release the button, it stays in the "pressed" state because the value is not being updated within the loop. To fix this issue, you should continuously check the button state within the loop.

    #define buttonPin 2
    #define ledPin 6
    
    int buttonState = 0;
    int lastButtonState = 0; // Keep track of the previous button state
    int brightness = 0;
    int fadeAmount = 5;
    
    void setup() {
      pinMode(ledPin, OUTPUT);
      pinMode(buttonPin, INPUT);
    }
    
    void loop() {
      buttonState = digitalRead(buttonPin);
      
      // Check if the button state has changed
      if (buttonState != lastButtonState) {
        if (buttonState == HIGH) { // Button pressed
          fadeAmount = 5;
          brightness = 0;
        } else { // Button released
          fadeAmount = 0;
          brightness = 255;
        }
        lastButtonState = buttonState;
      }
      
      analogWrite(ledPin, brightness);
      
      // Fade the LED when the button is pressed
      if (buttonState == HIGH) {
        if (brightness <= 255) {
          brightness = brightness + fadeAmount;
        }
        if (brightness > 255) {
          brightness = 0; // Reset brightness when it reaches 255
        }
        delay(80);
      }
    }