如何让覆盖按钮在淡入淡出循环中起作用

How to get an override button functioning in a fade loop

我正在尝试允许一个按钮覆盖我的 LED,该 LED 设置为反复淡入淡出。相反,该按钮只是简单地关闭了微控制器 Adafruit Huzzah ESP8266 本身的 LED,对引脚 13 LED 没有影响。

代码:

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);
}

如下更改循环并尝试,

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);
}