ESP32 + SSD1306 OLED 显示中文天气与网络时间(U8g2 + WiFi + NTP 完整实战)

一、简介

本文基于 ESP32 开发板 + SSD1306 128×64 OLED 显示屏,实现一个完整的物联网小项目,功能包括:

  • ESP32 通过 I2C 驱动 OLED
  • 使用 U8g2 库显示中文(无外置字库)
  • 通过 HTTP 请求天气 API 获取实时天气
  • 使用 NTP 网络时间协议自动校时
  • OLED 实时显示:日期、时间、城市、温度、天气情况
  • 自动刷新时间,天气数据动态更新

适合作为 ESP32 + OLED + 网络通信 的综合入门示例。


二、硬件连接说明

1. 接线方式(SSD1306 I2C)

OLED 引脚 ESP32 引脚
VCC 3V3
GND GND
SDA GPIO 21
SCL GPIO 22

ESP32 默认 I2C 引脚:

SDA → GPIO21,SCL → GPIO22


三、软件环境与依赖库

1. 开发环境

  • Arduino IDE(或 PlatformIO)
  • ESP32 Board Support Package

2. 需要安装的库

text 复制代码
U8g2
ArduinoJson
NTPClient

WiFi.hHTTPClient.h 为 ESP32 自带库。


四、天气 API 说明

本文使用的天气接口:

text 复制代码
http://t.weather.itboy.net/api/weather/city/101010100

特点:

  • 免费
  • 无需 Key
  • 返回 JSON,支持中文
  • 城市通过城市代码区分

五、完整示例代码(已添加中文注释)

⚠️ 以下代码为 最终整合版本

  • 中文显示
  • 天气获取
  • NTP 自动更新时间
  • OLED 实时刷新
cpp 复制代码
#include <Wire.h>
#include <U8g2lib.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <NTPClient.h>
#include <WiFiUdp.h>

/* ================= WiFi 配置 ================= */
const char* ssid = "wifi帐号";
const char* password = "Wifi密码";

/* ================= 天气 API ================= */
String apiUrl = "http://t.weather.itboy.net/api/weather/city/101010100";

/* ================= OLED 初始化 =================
   使用硬件 I2C,ESP32 默认:
   SDA -> GPIO21
   SCL -> GPIO22
*/
U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(
  U8G2_R0,
  U8X8_PIN_NONE,
  SCL,
  SDA
);

/* ================= NTP 时间配置 =================
   时区偏移:28800 秒(UTC+8,中国时间)
   更新时间间隔:60000 ms
*/
WiFiUDP udp;
NTPClient timeClient(udp, "pool.ntp.org", 28800, 60000);

/* ================= 刷新控制 ================= */
unsigned long lastUpdateTime = 0;
unsigned long interval = 1000;  // 每秒刷新一次显示

/* ================= 天气数据结构体 ================= */
struct WeatherData {
  String city;          // 城市
  String temperature;   // 温度
  String weatherType;   // 天气类型
  String timedate;      // 日期时间
};

void setup() {
  Serial.begin(115200);

  /* -------- 连接 WiFi -------- */
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }

  Serial.println("\nWiFi Connected");
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());

  /* -------- OLED 初始化 -------- */
  u8g2.begin();
  u8g2.enableUTF8Print();  // 必须开启 UTF-8,否则中文乱码

  /* -------- 启动 NTP -------- */
  timeClient.begin();
}

void loop() {
  unsigned long currentMillis = millis();

  /* 每秒更新一次显示 */
  if (currentMillis - lastUpdateTime >= interval) {
    lastUpdateTime = currentMillis;

    // 获取天气数据
    WeatherData weatherData = getWeatherData();

    if (weatherData.city != "") {
      // 更新时间
      timeClient.update();
      String currentTime = timeClient.getFormattedTime();

      // OLED 显示
      u8g2.clearBuffer();
      u8g2.setFont(u8g2_font_wqy12_t_gb2312);  // 中文字体

      u8g2.setCursor(0, 15);
      u8g2.print("日期: " + extractDate(weatherData.timedate) + " " + currentTime);

      u8g2.setCursor(0, 30);
      u8g2.print("城市: " + weatherData.city);

      u8g2.setCursor(0, 45);
      u8g2.print("温度: " + weatherData.temperature);

      u8g2.setCursor(0, 60);
      u8g2.print("天气: " + weatherData.weatherType);

      u8g2.sendBuffer();
    }
  }
}

/* ================= 获取天气数据 ================= */
WeatherData getWeatherData() {
  HTTPClient http;
  WeatherData weatherData;

  http.begin(apiUrl);
  int httpCode = http.GET();

  if (httpCode == 200) {
    String payload = http.getString();
    Serial.println(payload);

    DynamicJsonDocument doc(1024);
    DeserializationError error = deserializeJson(doc, payload);

    if (!error) {
      weatherData.timedate = doc["time"].as<String>();
      weatherData.city = doc["cityInfo"]["city"].as<String>();
      weatherData.temperature = doc["data"]["wendu"].as<String>();
      weatherData.weatherType = doc["data"]["forecast"][0]["type"].as<String>();
    }
  }

  http.end();
  return weatherData;
}

/* ================= 日期格式处理 =================
   输入:YYYY-MM-DD HH:MM:SS
   输出:MM-DD
*/
String extractDate(String fullDate) {
  int spaceIndex = fullDate.indexOf(' ');
  String datePart = fullDate.substring(0, spaceIndex);
  return datePart.substring(5);
}

六、关键技术点总结

  1. U8g2 显示中文

    • 必须使用 u8g2_font_wqy12_t_gb2312
    • 必须调用 enableUTF8Print()
  2. ESP32 网络请求

    • 使用 HTTPClient
    • JSON 解析推荐 ArduinoJson
  3. 时间自动更新

    • NTPClient 负责时间
    • millis() 控制刷新频率,避免阻塞
  4. 性能注意

    • 不建议每秒请求天气 API
    • 可后续改为:天气 10 分钟更新一次,时间每秒更新
相关推荐
LCG元14 小时前
STM32+ESP8266+MQTT 物联网气象站:从零搭建温湿度远程监测系统(附完整源码)
stm32·物联网·struts
殷忆枫16 小时前
基于K210与STM32的智能垃圾分类与物联网监管系统
stm32·物联网·分类
老孙讲技术21 小时前
【4G IPC 上云】临时点位怎么免布线上云?listDeviceDetailsByPage + 辅码流预览|智慧工地实战
后端·物联网
数字新视界1 天前
信创动环监控厂家深入剖析智能机房环境监控技术应用与挑战
服务器·数据库·物联网·芯片·动环监控系统
笨鸟先飞,勤能补拙1 天前
AI Agent应用领域深度解析:从概念到落地的全维度审视
大数据·人工智能·python·物联网·安全·网络安全·github
星恒讯工业路由器2 天前
当无人机成为“空中路由器”:应急通信背后的联网技术支撑
物联网·信息与通信·wifi模块·无人机模块·无人机应急通信·空中基站·三断通信
会周易的程序员2 天前
aiDgePLC — IEC61131-3 ST PLC 虚拟机调试与运行环境
c++·物联网·虚拟机·st·工业协议·iec61131·梯形图
老孙讲技术2 天前
周末档期厨房爆单,带宽账单也爆了——不是直播难,是主码流 + always 计划在烧钱
后端·物联网
老孙讲技术2 天前
校园开放日前夜才说要「全校透明」?我用轻应用把 9 路教室预览和回放嵌进了校园后台
后端·物联网
Kingexpand_com2 天前
物联网APP开发该选原生还是跨平台?场景选型详解
物联网·物联网app·物联网app定制开发·物联网开发公司