esp8266天气时钟0.96寸oled代码
时间: 2023-07-02 14:03:42 浏览: 235
以下是基于esp8266和0.96寸OLED显示屏的天气时钟代码,采用了BME280传感器获取温度、湿度和气压数据,并通过WiFi连接获取天气信息并实时更新显示:
```c++
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <SSD1306Wire.h>
#include <OLEDDisplayUi.h>
// WiFi设置
const char* ssid = "YourSSID"; // 你的WiFi名称
const char* password = "YourPassword"; // 你的WiFi密码
// 服务器设置
const String serverName = "http://api.openweathermap.org/data/2.5/weather?q=Shenzhen&appid=YourAPIKey"; // 你的OpenWeatherMap API Key和城市名称
// OLED显示屏设置
SSD1306Wire display(0x3c, D2, D1);
OLEDDisplayUi ui(&display);
// BME280传感器设置
Adafruit_BME280 bme;
// 时间设置
unsigned long currentTime = millis();
unsigned long previousTime = 0;
const long interval = 60000; // 更新时间间隔,单位为毫秒
void setup() {
Serial.begin(115200);
// 初始化OLED显示屏
display.init();
display.setContrast(255);
display.setFont(ArialMT_Plain_10);
// 初始化BME280传感器
if (!bme.begin(0x76)) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
}
// 连接WiFi
WiFi.begin(ssid, password);
Serial.print("Connecting to ");
Serial.println(ssid);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
}
void loop() {
currentTime = millis();
if (currentTime - previousTime >= interval) {
// 获取天气信息
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(serverName);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String payload = http.getString();
Serial.println(payload);
// 解析JSON数据
const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(4) + 60;
DynamicJsonDocument doc(capacity);
deserializeJson(doc, payload);
const char* description = doc["weather"][0]["description"];
float temp = doc["main"]["temp"];
float humidity = doc["main"]["humidity"];
float pressure = doc["main"]["pressure"];
// 显示天气信息
display.clear();
display.drawString(0, 0, "Weather in Shenzhen");
display.drawString(0, 12, description);
display.drawString(0, 24, "Temp: " + String(temp) + " C");
display.drawString(0, 36, "Humidity: " + String(humidity) + " %");
display.drawString(0, 48, "Pressure: " + String(pressure) + " hPa");
display.display();
} else {
Serial.println("Error on HTTP request");
}
http.end();
} else {
Serial.println("WiFi Disconnected");
}
previousTime = currentTime;
}
}
```
需要注意的是,需要在OpenWeatherMap网站上注册账号并申请API Key,替换代码中的YourAPIKey和城市名称。
此外,如果你的OLED显示屏型号不同,可能需要修改相关的设置。
阅读全文