#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "RTClib.h"
#include <Keypad.h>
RTC_DS1307 rtc;
LiquidCrystal_I2C lcd(0x27, 16, 2);
const byte ROW_NUM = 4; // Number of rows in the keypad
const byte COLUMN_NUM = 4; // Number of columns in the keypad
char keys[ROW_NUM][COLUMN_NUM] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte pin_rows[ROW_NUM] = {9, 8, 7, 6}; // Connect to the row pinouts of the keypad
byte pin_column[COLUMN_NUM] = {5, 4, 3, 2}; // Connect to the column pinouts of the keypad
int buzzerPin = 13;
DateTime alarmTime;
bool alarmEnabled = false;
void setup () {
Serial.begin(9600);
lcd.begin(16, 2);
lcd.backlight();
if (!rtc.begin()) {
lcd.print("Couldn't find RTC");
while (1);
}
if (!rtc.isrunning()) {
lcd.print("RTC is NOT running!");
}
}
void loop () {
checkKeypad();
DateTime now = rtc.now();
displayTime(now);
if (alarmEnabled && now.hour() == alarmTime.hour() && now.minute() == alarmTime.minute()) {
activateAlarm();
}
delay(1000);
}
void checkKeypad() {
char key = getKey();
if (key) {
handleKeyPress(key);
delay(500); // Debounce
}
}
char getKey() {
for (int i = 0; i < ROW_NUM; i++) {
pinMode(pin_rows[i], OUTPUT);
digitalWrite(pin_rows[i], LOW);
for (int j = 0; j < COLUMN_NUM; j++) {
if (digitalRead(pin_column[j]) == LOW) {
delay(50);
return keys[i][j];
}
}
pinMode(pin_rows[i], INPUT);
}
return 0;
}
void handleKeyPress(char key) {
switch (key) {
case 'A':
setAlarm();
break;
case 'B':
disableAlarm();
break;
default:
break;
}
}
void setAlarm() {
lcd.clear();
lcd.print("Set Alarm");
int hour = setDigit("Hour", 24);
int minute = setDigit("Minute", 60);
alarmTime = DateTime(alarmTime.year(), alarmTime.month(), alarmTime.day(), hour, minute, 0);
alarmEnabled = true;
lcd.clear();
lcd.print("Alarm Set");
delay(1000);
}
int setDigit(const char* label, int maxVal) {
lcd.clear();
lcd.print(label);
int digit = -1;
while (digit < 0 || digit >= maxVal) {
char key = getKey();
if (key >= '0' && key <= '9') {
digit = key - '0';
lcd.setCursor(0, 1);
lcd.print(digit);
}
}
delay(500);
return digit;
}
void disableAlarm() {
alarmEnabled = false;
lcd.clear();
lcd.print("Alarm Disabled");
delay(1000);
}
void displayTime(DateTime now) {
lcd.clear();
lcd.print(now.toString("yyyy-MM-dd"));
lcd.setCursor(0, 1);
lcd.print(now.toString("HH:mm:ss"));
}
void activateAlarm() {
tone(buzzerPin, 1000);
delay(5000);
noTone(buzzerPin);
disableAlarm();
}