如何把esp8266和oled屏幕连接起来显示天气
时间: 2023-05-14 10:05:20 浏览: 151
ESP8266项目篇OLED天气时钟
5星 · 资源好评率100%
您可以使用ESP8266和OLED屏幕的I2C接口来连接它们。您需要使用适当的库来连接它们,并使用天气API获取天气数据。然后,您可以将数据显示在OLED屏幕上。以下是一个简单的示例代码:
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
#define OLED_RESET 0
Adafruit_SSD1306 display(OLED_RESET);
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* serverName = "http://api.openweathermap.org/data/2.5/weather?q=your_CITY&appid=your_API_KEY&units=metric";
void setup() {
Serial.begin(9600);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
display.display();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
display.println("Weather in your_CITY:");
display.display();
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(serverName);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String payload = http.getString();
DynamicJsonDocument doc(1024);
deserializeJson(doc, payload);
float temp = doc["main"]["temp"];
String description = doc["weather"][0]["description"];
display.setCursor(0,10);
display.println("Temperature: " + String(temp) + "C");
display.setCursor(0,20);
display.println("Description: " + description);
display.display();
} else {
Serial.println("Error on HTTP request");
}
http.end();
}
delay(60000);
}
阅读全文