Search code examples
arduinoesp8266arduino-esp8266adafruit

How to get an override button functioning in a fade loop


I am trying to allow for a button to override my LED which is set to fade in and out repeatedly. Instead, the button simply turns off the led on the microcontroller Adafruit Huzzah ESP8266 itself and has no effect on the pin 13 LED.

Code:

const int buttonPin = 2;     // the number of the pushbutton pin
int ledPin = 13;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by
    int buttonState = 0;         // variable for reading the pushbutton status

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

void loop() {
  buttonState = digitalRead(buttonPin);

  if (buttonState == LOW) {
    digitalWrite(ledPin, LOW);
  } else {
    digitalWrite(ledPin, HIGH);
  }
  analogWrite(ledPin, brightness);
  buttonState = digitalRead(buttonPin);

  brightness = brightness + fadeAmount;

  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}

Solution

  • Change your loop as below and try,

    void loop() {
      buttonState = digitalRead(buttonPin);
    
      if (buttonState == LOW) {
        digitalWrite(ledPin, LOW);
      } else {
        analogWrite(ledPin, brightness);
      }
    
      buttonState = digitalRead(buttonPin);
    
      brightness = brightness + fadeAmount;
    
      if (brightness <= 0 || brightness >= 255) {
        fadeAmount = -fadeAmount;
      }
      // wait for 30 milliseconds to see the dimming effect
      delay(30);
    }