#include <LiquidCrystal_I2C.h>
#include <TimeLib.h> // 引入TimeLib库来处理时间和NTP
// 初始化I2C液晶显示屏
LiquidCrystal_I2C LCD(0x27, 16, 2); // 0x27是LCD的I2C地址,16和2分别代表字符数和行数
// NTP服务器和时区设置
const char* ntpServer = "pool.ntp.org";
const long utcOffset = 8 * 3600; // UTC偏移量,东八区
const long utcOffsetDST = 0; // 夏令时偏移量
// spinner函数,用于显示加载动画
void spinner() {
static int8_t counter = 0;
const char* glyphs = "\xa1\xa5\xdb"; // 这里定义了三个字符作为加载动画
LCD.setCursor(15, 1); // 将光标设置到第二行中间位置
LCD.print(glyphs[counter++]); // 打印当前字符
if (counter == sizeof(glyphs) - 1) { // 如果动画完成一个周期
counter = 0; // 重置计数器
}
}
// printLocalTime函数,用于显示本地时间
void printLocalTime() {
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
LCD.setCursor(0, 1);
LCD.print("Connection Err");
return;
}
LCD.setCursor(8, 0); // 设置时间显示的位置
LCD.print(&timeinfo, "%H:%M:%S"); // 显示时间
LCD.setCursor(0, 1); // 设置日期显示的位置
LCD.printIn(&timeinfo, "%d/%m/%Y"); // 显示日期
}
void setup() {
Serial.begin(115200);
LCD.begin(); // 初始化LCD
LCD.backlight(); // 打开背光
setSyncProvider(getNtpTime); // 设置NTP时间同步提供者
if(timeStatus() != timeNotSet) {
setSyncInterval(3600); // 每小时同步一次时间
}
}
void loop() {
printLocalTime(); // 显示时间
delay(1000); // 等待1秒
spinner(); // 显示加载动画
delay(100); // 等待100毫秒
}