简体   繁体   English

为什么LED不熄灭?

[英]Why doesn't the LED turn off?

I have a program (copied below) that has an alarm that starts in 10 seconds, which starts a LED that blinks every two seconds. 我有一个程序(在下面复制),该程序有一个在10秒内启动的警报,它将启动一个每两秒闪烁一次的LED。 I would like to push a button that turns off the alarm / LED. 我想按下一个按钮以关闭警报/ LED。 The LED blinks as intended but does not turn off when I push the button. 当我按下按钮时,LED会按预期闪烁,但不会熄灭。 Any idea why? 知道为什么吗? Code below: 代码如下:

#include <Time.h>
#include <TimeAlarms.h>
#define buttonPin 2 // assigns pin 2 as buttonPin
#define ledPin 13 // assigns pin 13 as ledPin

int buttonState; // variable for reading the pushbutton status
int lastButtonState = LOW;
unsigned long lastDebounceTime = 0; // the last time the output pin was toggled
unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers

void setup() {
  Serial.begin(9600); // start Serial Monitor
  setTime(0, 0, 0, 1, 1, 2018); // set time to 00:00:00 Jan 1 2018
  Alarm.alarmRepeat(0, 0, 10, DailyAlarm); // Alarm triggered in 10 sec
  pinMode(ledPin, OUTPUT); // assigns ledPin as led output pin.
  pinMode(buttonPin, INPUT); // assigns buttonPin as input pin
  // digitalWrite(ledPin, ledState); // LED is off initially
}

void loop() {
  digitalClockDisplay();
  Alarm.delay(1000); // wait one second between clock display
  int reading = digitalRead(buttonPin);
  if (reading != lastButtonState) {
    lastDebounceTime = millis();
  }
  if ((millis() - lastDebounceTime) > debounceDelay) {
    if (reading != buttonState) {
      buttonState = HIGH;
      Serial.print(buttonState);
    }
  }
}

void DailyAlarm() {
  Serial.println("Alarm");
  while (buttonState == LOW) {
    blink(2000); // blink every 2s
  }
}

void blink(int period) {
  digitalWrite(ledPin, HIGH);
  delay(period / 2);
  digitalWrite(ledPin, LOW);
  delay(period / 2);
}

void digitalClockDisplay() {
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.println();
}

void printDigits(int digits) {
  Serial.print(":");
  if (digits < 10)
    Serial.print('0');
  Serial.print(digits);
}
int buttonState; // variable for reading the pushbutton status

You haven't initialized the button state 您尚未初始化按钮状态

Try 尝试

boolean buttonState = LOW

And Don't mix integers and booleans use this 而且不要混合使用整数和布尔值

boolean lastButtonState = LOW;

instead of 代替

int lastButtonState = LOW;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM