ESP8266+0.96寸OLED+心知天气做的简约版天气时钟

时间:2025-02-28 08:38:09
#include <ESP8266WiFi.h> #include <ESP8266_Seniverse.h> #include <U8g2lib.h> #include <NTPClient.h> #include <WiFiUdp.h> #include <WiFiManager.h> U8G2_SSD1306_128X64_NONAME_F_4W_SW_SPI u8g2(U8G2_R0, /* clock=*/ 4, /* data=*/ 5, /* cs=*/ 12, /* dc=*/ 14, /* reset=*/ 13);/*DI ------ D1 D0 ------- D2 DC ------- D5 CS ------- D6 RES -------D7*/ // weather const String weathers[] = {"晴", "晴", "晴", "晴", "多云", "晴间多云", "晴间多云", "大部多云", "大部多云", "阴", "阵雨", "雷阵雨", "雷雨冰雹", "小雨", "中雨", "大雨", "暴雨", "大暴雨", "特大暴雨", "冻雨", "雨夹雪", "阵雪", "小雪", "中雪", "大雪", "暴雪", "浮尘", "扬沙", "沙尘暴", "强沙暴", "雾", "霾", "风", "大风", "飓风", "热带风暴", "龙卷风", "冷", "热", "未知" }; const char* ssid = "***"; // 连接WiFi名 const char* password = "***"; // 连接WiFi密码 String reqUserKey = "***";// 心知天气私钥 String reqLocation = "***";// 城市 String reqUnit = "c";// 摄氏/华氏 WeatherNow weatherNow; Forecast forecast; WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, "", 60 * 60 * 8, 30 * 60 * 1000); int times = 0; void setup() { Serial.begin(115200); u8g2.begin(); u8g2.enableUTF8Print(); u8g2.clearBuffer(); u8g2.sendBuffer(); delay(850); connectWiFi();// 连接wifi // 配置心知天气请求信息 weatherNow.config(reqUserKey, reqLocation, reqUnit); forecast.config(reqUserKey, reqLocation, reqUnit); timeClient.begin(); } void loop() { u8g2.clearBuffer();// 清空显示设备内部缓冲区 u8g2.setFont(u8g2_font_wqy12_t_gb2312); //天气 if (forecast.update()) { // 更新天气信息 //今天的天气、温度 u8g2.setCursor(43, 12); String str1 = weathers[forecast.getDayCode(0)] + " " + forecast.getLow(0) + "-" + forecast.getHigh(0) + "℃" + " " + "今"; u8g2.print(str1); //明天的天气、温度范围 u8g2.setCursor(43, 27); str1 = weathers[forecast.getDayCode(1)] + " " + forecast.getLow(1) + "-" + forecast.getHigh(1) + "℃" + " " + "明"; u8g2.print(str1); //后天的天气、温度范围 u8g2.setCursor(43, 42); str1 = weathers[forecast.getDayCode(2)] + " " + forecast.getLow(2) + "-" + forecast.getHigh(2) + "℃" + " " + "后"; u8g2.print(str1); } else {// 更新失败 //(53, 61); //(">_<...网络慢"); } //时间 u8g2.setFont(u8g2_font_wqy16_t_gb2312); if (timeClient.update()) { u8g2.setCursor(53, 61); String time = timeClient.getFormattedTime().substring(0, 5); u8g2.print(time); } else { //(53, 61); //(">_<...网络慢"); } u8g2.setFont(u8g2_font_unifont_t_symbols); //先设置字体字集 if (times == 0) { u8g2.drawGlyph(13, 18, 0x2603); u8g2.drawGlyph(13, 38, 0x2615); u8g2.drawGlyph(15, 58, 0x2600); times = 1; } else if (times == 1) { u8g2.drawGlyph(13, 18, 0x23f0); u8g2.drawGlyph(13, 38, 0x23f3); u8g2.drawGlyph(15, 58, 0x2614); times = 2; } else { u8g2.drawGlyph(13, 18, 0x2618); u8g2.drawGlyph(13, 38, 0x2619); u8g2.drawGlyph(15, 58, 0x2606); times = 0; } u8g2.sendBuffer();// 显示缓冲区内容 delay(10000); } // 连接WiFi void connectWiFi() { // 建立WiFiManager对象 WiFiManager wifiManager; // 自动连接WiFi。以下语句的参数是连接ESP8266时的WiFi名称 wifiManager.autoConnect("AutoConnectAP"); }