#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
#include <RTClib.h>
// I2C LCD's address
#define LCD_ADDRESS 0x27 // Your LCD I2C address may be different; check the LCD documentation
// LCD object
LiquidCrystal_I2C lcd(LCD_ADDRESS, 20, 4);
// Define Keypad's digital pins
const byte ROW_NUM = 4;
const byte COLUMN_NUM = 4;
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};
byte pin_column[COLUMN_NUM] = {5, 4, 3, 2};
Keypad keypad = Keypad(makeKeymap(keys), pin_rows, pin_column, ROW_NUM, COLUMN_NUM);
RTC_DS1307 rtc;
unsigned long currentTime = 0;
unsigned long refreshInterval = 1000; // 刷新间隔,单位:毫秒
int defaultYear = 2023;
int defaultMonth = 10;
int defaultDay = 17;
int setHour = 0;
int setMinute = 0;
int setSecond = 0;
boolean settingTime = false;
void setup() {
Wire.begin();
rtc.begin();
if (!rtc.isrunning()) {
Serial.println("RTC is NOT running!");
// 设置默认时间
rtc.adjust(DateTime(defaultYear, defaultMonth, defaultDay, 0, 0, 0));
}
lcd.begin(20, 4); // 20 columns, 4 rows
lcd.backlight(); // Turn on the backlight
lcd.setCursor(0, 0);
lcd.print("Digital Clock");
delay(2000);
}
void loop() {
char key = keypad.getKey();
if (key) {
if (key == 'A') {
showDateTime();
} else if (key == 'B') {
// 进入设置模式
settingTime = true;
setClock();
settingTime = false;
delay(2000); // 延迟一段时间以确保设置被应用
}
}
updateClock();
delay(10); // 防止过于频繁的刷新
}
void updateClock() {
if (millis() - currentTime >= refreshInterval) {
currentTime = millis();
if (!settingTime) {
showDateTime();
}
}
}
void showDateTime() {
DateTime now = rtc.now();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Time: ");
lcd.print(now.hour(), DEC);
lcd.print(':');
lcd.print(now.minute(), DEC);
lcd.print(':');
lcd.print(now.second(), DEC);
lcd.setCursor(0, 2);
lcd.print("Date: ");
lcd.print(now.year(), DEC);
lcd.print('/');
lcd.print(now.month(), DEC);
lcd.print('/');
lcd.print(now.day(), DEC);
}
void setClock() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Set Hour: ");
setHour = setNumericValue();
lcd.setCursor(0, 1);
lcd.print("Set Minute: ");
setMinute = setNumericValue();
lcd.setCursor(0, 2);
lcd.print("Set Second: ");
setSecond = setNumericValue();
DateTime newTime = rtc.now();
newTime = DateTime(newTime.year(), newTime.month(), newTime.day(), setHour, setMinute, setSecond);
rtc.adjust(newTime);
}
int setNumericValue() {
int value = 0;
char key;
while (true) {
key = keypad.getKey();
if (key >= '0' && key <= '9') {
lcd.print(key);
value = value * 10 + (key - '0');
} else if (key == '#') {
break;
}
delay(100);
}
return value;
}