|
通過(guò)使用定時(shí)器模塊來(lái)實(shí)現(xiàn)按鍵可調(diào)的鬧鐘功能。具體操作如下:
定義一個(gè)變量alarm_time用于存儲(chǔ)用戶設(shè)置的鬧鐘時(shí)間戳;
當(dāng)按下鬧鐘鍵時(shí),啟動(dòng)定時(shí)器并設(shè)置定時(shí)器的計(jì)時(shí)時(shí)間為alarm_time;
每次定時(shí)器中斷發(fā)生時(shí),判斷是否已經(jīng)超過(guò)設(shè)定的時(shí)間點(diǎn),如果超過(guò)了則響鈴提示;
如果沒(méi)有超過(guò)設(shè)定的時(shí)間點(diǎn),則重新設(shè)置定時(shí)器的計(jì)時(shí)時(shí)間為當(dāng)前時(shí)刻加上一段延時(shí)時(shí)間,以便下次定時(shí)器中斷時(shí)再次響鈴提示。
另外還需要添加一個(gè)按鈕來(lái)停止鬧鐘。當(dāng)按下該按鈕時(shí),終止定時(shí)器循環(huán)并將alarm_time置為-1表示取消鬧鐘。
同時(shí)需要添加一些顯示界面來(lái)讓用戶可以查看當(dāng)前的鬧鐘狀態(tài)以及修改鬧鐘時(shí)間等操作。
具體的代碼實(shí)現(xiàn)可以參考下面的示例:
// 定義一個(gè)變量保存用戶設(shè)置的鬧鐘時(shí)間戳
unsigned int alarm_time = -1; // 初始值為未設(shè)鬧鐘
void timer() {
if (alarm_time != -1) { // 若設(shè)置了鬧鐘,則響鈴提示
if ((int)(millis()) > alarm_time) { // 已到設(shè)定的時(shí)間點(diǎn)
beep(); // 響鈴提示
alarm_time = -1; // 清空鬧鐘時(shí)間戳
} else {
delay(ALARM_INTERVAL); // 延時(shí)一定時(shí)間后再次響鈴提醒
}
}
}
void setup() {
pinMode(BUTTON, INPUT); // 配置按扭傳感器引腳為輸入模式
attachInterrupt(digitalPinToInterruptNumber(BUTTON), buttonPressed, FALLING); // 注冊(cè)按鍵觸發(fā)的中斷函數(shù)
setAlarmTime(-1); // 初始化鬧鐘時(shí)間戳為未設(shè)鬧鐘
}
void loop() {
while (!buttonPressed()); // 直到按下按鈕才跳出循環(huán)體
clearButtonPressedFlag(); // 釋放按鍵觸發(fā)的中斷標(biāo)志位
setAlarmTime(userInputGetCurrentDateTime()); // 根據(jù)用戶的選擇設(shè)置新的鬧鐘時(shí)間
startTimer(); // 開(kāi)啟定時(shí)器循環(huán)
displaySetText(""); // 清除顯示屏上的內(nèi)容
displayClearDisplay(); // 清除顯示屏上所有的字符
displayPrintf("%d", userInputGetCurrentDateTime().hour);
displayPrintf(":%d", userInputGetCurrentDateTime().minute);
displayPrintf(":%d", userInputGetCurrentDateTime().second);
displayPrintf(" ");
displayPrintf("%s", "Alarm Time");
displayPrintf(" %d ", getAlarmTime());
displayUpdateScreen(); // 刷新顯示屏的內(nèi)容
stopTimer(); // 關(guān)閉定時(shí)器循環(huán)
}
void buttonPressed() {
return !digitalRead(BUTTON); // 按扭傳感器輸出高電平即為按下按鈕
}
void setAlarmTime(uint8_t time) {
uint8_t old_value = alarm_time;
alarm_time = time;
if (old_value == -1 && alarm_time != -1) { // 從未設(shè)鬧鐘變?yōu)樵O(shè)了鬧鐘
startTimer(); // 打開(kāi)定時(shí)器循環(huán)
} else if (old_value != -1 && alarm_time == -1) { // 從有鬧鐘變成無(wú)鬧鐘
stopTimer(); // 關(guān)閉定時(shí)器循環(huán)
}
}
void startTimer() {
noInterrupts();
TCNT0 = (F_CPU / ALARM_CLOCK)/PRESCALE;
ICR1 |= _BV(ICIE1);
interrupts();
}
void stopTimer() {
noInterrupts();
IC1R &= ~(_BV(ICEN1));
interrupts();
}
以上是使用ATmega328p單片機(jī)的示例代碼,其他型號(hào)的單片機(jī)也可以根據(jù)自己的實(shí)際情況進(jìn)行相應(yīng)的調(diào)整
|
評(píng)分
-
查看全部評(píng)分
|