#include <LiquidCrystal.h> // 初始化LiquidCrystal库,指定接口引脚
LiquidCrystal lcd(12, 11, 10, 9, 8, 7); // 创建一个LiquidCrystal对象
const int buttonStart = 2; // 开始按钮引脚
const int buttonAdd = 3; // 增加时间按钮引脚
const int buttonSubtract = 4; // 减少时间按钮引脚
const int buzzer = 5; // 蜂鸣器引脚
unsigned long timer = 0; // 定时器时长(以秒为单位)
unsigned long currentTime = 0; // 当前时间戳
bool timerStarted = false; // 定时器是否已启动
void setup() {
// 初始化串行通信
Serial.begin(9600);
// 初始化LCD显示器
lcd.begin(16, 2);
lcd.setCursor(0, 0);
lcd.print("Set timer: 0 s");
// 配置按钮为输入模式,启用内置上拉电阻
pinMode(buttonStart, INPUT_PULLUP);
pinMode(buttonAdd, INPUT_PULLUP);
pinMode(buttonSubtract, INPUT_PULLUP);
// 设置蜂鸣器引脚为输出
pinMode(buzzer, OUTPUT);
// 将A0~A5设置为LED控制的输出引脚
for (int pin = A0; pin <= A5; ++pin) {
pinMode(pin, OUTPUT);
}
}
void loop() {
// 检查增加时间按钮
if (digitalRead(buttonAdd) == LOW) {
while (digitalRead(buttonAdd) == LOW); // 简单防抖处理
timer += 10; // 增加1分钟
}
// 检查减少时间按钮
if (digitalRead(buttonSubtract) == LOW) {
while (digitalRead(buttonSubtract) == LOW); // 简单防抖处理
if (timer > 10) {
timer -= 10; // 减少1分钟
}
}
// 检查开始按钮
if (digitalRead(buttonStart) == LOW) {
while (digitalRead(buttonStart) == LOW); // 简单防抖处理
timerStarted = !timerStarted; // 启动或暂停定时器
if (timerStarted) {
currentTime = millis();
}
}
// 定时器逻辑处理
if (timerStarted && (millis() - currentTime >= timer * 1000)) {
playMusic();
lcd.clear();
lcd.print("Time's up!");
delay(2000); // 显示消息2秒
timerStarted = false; // 停止定时器
timer = 0; // 重置定时器
} else if (timerStarted) {
lcd.clear();
unsigned long remainingTime = timer - ((millis() - currentTime) / 1000);
lcd.setCursor(0, 0);
lcd.print("Time left: ");
lcd.print(remainingTime);
lcd.print(" s");
} else {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Set timer: ");
lcd.print(timer);
lcd.print(" s");
}
}
void playMusic() {
// 演奏“Twinkle Twinkle Little Star”
int melody[] = {
262, 262, 392, 392, 440, 440, 392,
349, 349, 330, 330, 294, 294, 262
};
// 每个音符的时长:4 = 四分音符, 2 = 二分音符,等等
int noteDurations[] = {
4, 4, 4, 4, 4, 4, 2,
4, 4, 4, 4, 4, 4, 2
};
int notes = sizeof(melody) / sizeof(melody[0]);
for (int thisNote = 0; thisNote < notes; thisNote++) {
// 计算音符时长
int noteDuration = 1000 / noteDurations[thisNote];
tone(buzzer, melody[thisNote], noteDuration);
// 控制A0~A5实现流水灯效果
for (int pin = A0; pin <= A5; ++pin) {
digitalWrite(pin, HIGH);
delay(noteDuration / 6);
digitalWrite(pin, LOW);
}
// 音符之间的暂停
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
noTone(buzzer); // 停止当前音符
}
}