Arduino esp8266天气预报
时间: 2023-10-09 09:13:23 浏览: 239
要使用Arduino ESP8266获取天气预报,你需要以下材料:
- Arduino ESP8266开发板
- DHT11温湿度传感器
- OLED显示屏
- 天气API密钥
步骤:
1. 首先,连接DHT11传感器到ESP8266,将其连接到引脚D1上。
2. 然后,连接OLED显示屏到ESP8266,将其连接到引脚D3和D4上。
3. 下载并安装Arduino IDE。
4. 在Arduino IDE中,打开串口监视器,并将波特率设置为115200。
5. 在Arduino IDE中,打开新的项目,并将以下代码复制到代码编辑器中:
#include <ESP8266WiFi.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <DHT.h>
#include <ArduinoJson.h>
#define DHTPIN D1
#define DHTTYPE DHT11
#define OLED_RESET 0
Adafruit_SSD1306 display(OLED_RESET);
DHT dht(DHTPIN, DHTTYPE);
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* host = "api.openweathermap.org";
const char* url = "/data/2.5/weather?q=Shanghai&appid=YOUR_API_KEY";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
display.setTextColor(WHITE);
display.setTextSize(1);
display.setCursor(0,0);
display.println("Weather Forecast:");
display.display();
dht.begin();
}
void loop() {
delay(2000);
WiFiClient client;
if (!client.connect(host, 80)) {
Serial.println("Connection failed");
return;
}
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
while (!client.available()) {
delay(100);
}
String line;
while (client.available()) {
line = client.readStringUntil('\r');
}
const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(5) + 70;
DynamicJsonDocument doc(capacity);
deserializeJson(doc, line);
JsonObject main = doc["main"];
double temperature = main["temp"];
double humidity = main["humidity"];
JsonObject wind = doc["wind"];
double windspeed = wind["speed"];
JsonObject weather = doc["weather"][0];
const char* description = weather["description"];
Serial.println("Temperature: " + String(temperature));
Serial.println("Humidity: " + String(humidity));
Serial.println("Wind speed: " + String(windspeed));
Serial.println("Description: " + String(description));
display.clearDisplay();
display.setCursor(0,0);
display.println("Temperature: " + String(temperature) + "C");
display.setCursor(0,10);
display.println("Humidity: " + String(humidity) + "%");
display.setCursor(0,20);
display.println("Wind speed: " + String(windspeed) + "m/s");
display.setCursor(0,30);
display.println("Description: " + String(description));
display.display();
}
6. 将代码中的ssid,password和YOUR_API_KEY更改为你的WiFi SSID,密码和天气API密钥。
7. 上传代码到ESP8266,并在串口监视器中查看结果。
8. 你现在应该可以看到连接到ESP8266的OLED显示屏上的天气预报信息。
这就是如何使用Arduino ESP8266获取天气预报的简单过程。
阅读全文