基于ESP32的天气时钟

项目介绍
这是一款基于ESP32和1.54寸TFT显示屏的智能天气时钟,通过WiFi连接获取实时天气信息和NTP时间,并通过精心设计的UI界面展示。
核心代码实现
基础配置与初始化
weather_clock.ino
// 包含必要的库文件
#include
#include
#include
#include
#include
#include
#include
TFT_eSPI tft = TFT_eSPI();
const char* wifiname = "yiyang"; // wifi名称
const char* wifipass = "lly20030601"; // wifi密码
// NTP服务器配置
const char* ntpServerName = "cn.pool.ntp.org";
const int utcOffset = 8; // 中国时区偏移量
// 心知天气API
const char* weatherApiUrl = "https://api.seniverse.com/v3/weather/now.json?"
"key=SSJM2-XW2HFEEH2tF&location=hangzhou&language=zh-Hans&unit=c";
// 天气数据结构
struct WeatherData {
String City; // 城市代码
int description; // 天气代码
double temperature; // 温度
};
天气数据获取
weather_clock.ino
void getWeatherData() {
HTTPClient http;
http.begin(weatherApiUrl);
int httpCode = http.GET();
if (httpCode == HTTP_CODE_OK) {
String weatherData = http.getString();
DynamicJsonDocument doc(1024);
deserializeJson(doc, weatherData);
// 解析天气数据
weather.City = doc["results"][0]["location"]["name"].as();
weather.description = doc["results"][0]["now"]["code"].as();
weather.temperature = doc["results"][0]["now"]["temperature"].as();
// 显示日期信息
struct tm timeinfo;
time_t now = timeClient.getEpochTime();
gmtime_r(&now, &timeinfo);
tft.setCursor(0, 65);
tft.setTextSize(4);
tft.print(timeinfo.tm_mon + 1);
tft.print('.');
tft.print(timeinfo.tm_mday);
}
http.end();
}
时间显示函数
weather_clock.ino
void displaytime() {
tft.setTextSize(2);
tft.setCursor(10, 110);
tft.fillRect(0, 110, 240, 130, TFT_WHITE); // 清空显示区域
// 获取当前时间
int hours = timeClient.getHours();
int minutes = timeClient.getMinutes();
int seconds = timeClient.getSeconds();
// 显示时间
tft.setTextSize(5);
tft.print(hours);
tft.print(":");
tft.print(minutes);
tft.setTextSize(4);
tft.print(":");
tft.println(seconds);
}
硬件组成
- ESP32主控
- 1.54寸TFT显示屏(ST7789驱动)
- WiFi模块(ESP32内置)
主要功能
- 实时天气显示
- NTP网络时间同步
- 自定义图形界面
- 定时自动更新
- 中文图标显示
第一阶段:硬件配置
- TFT显示屏驱动配置
- ESP32引脚定义
- WiFi连接功能
- NTP时间同步
第二阶段:天气功能
- 心知天气API接入
- HTTP请求处理
- JSON数据解析
- 天气信息存储结构设计
第三阶段:界面设计
- UI界面布局设计
- 中文图标制作
- 天气图标设计
- 定时器实现自动更新
技术特点
- 使用TFT_eSPI库驱动显示屏
- 通过图片方式显示中文
- 心知天气API实时数据获取
- ESP32定时器中断实现自动更新
- 模块化的界面设计
界面布局
- 标题区域
- 地区显示
- 天气图标
- 日期显示
- 星期显示
- 时间显示
- DIY自定义区域