2

我有一个程序(复制如下),它有一个在 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);
}
4

1 回答 1

0
int buttonState; // variable for reading the pushbutton status

你还没有初始化按钮状态

尝试

boolean buttonState = LOW

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

boolean lastButtonState = LOW;

代替

int lastButtonState = LOW;
于 2019-03-29T10:40:56.577 回答