为什么LED没有关闭?

问题描述 投票:2回答:1

我有一个程序(复制如下),它有一个在10秒钟内启动的警报,启动一个每两秒闪烁一次的LED。我想按下一个关闭闹钟/ LED的按钮。 LED按预期闪烁,但按下按钮时不会关闭。知道为什么吗?代码如下:

#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);
}
timer arduino arduino-uno alarm debounce
1个回答
0
投票
int buttonState; // variable for reading the pushbutton status

您尚未初始化按钮状态

尝试

boolean buttonState = LOW

并且不要混合整数和布尔值使用它

boolean lastButtonState = LOW;

代替

int lastButtonState = LOW;
© www.soinside.com 2019 - 2024. All rights reserved.