你能写一段esp8266获取天气的代码吗
时间: 2024-03-14 14:46:23 浏览: 25
当然可以,以下是一个简单的示例代码:
```c++
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* host = "api.openweathermap.org";
const String city = "Shenzhen";
const String apiKey = "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");
}
void loop() {
WiFiClientSecure client;
if (!client.connect(host, 443)) {
Serial.println("Connection failed");
return;
}
String url = "/data/2.5/weather?q=" + city + "&appid=" + apiKey;
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: ESP8266\r\n" +
"Connection: close\r\n\r\n");
while (!client.available()) {
delay(100);
}
String response = client.readString();
Serial.println(response);
const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(4) + 70;
DynamicJsonDocument doc(capacity);
deserializeJson(doc, response);
JsonObject main = doc["main"];
double temperature = main["temp"];
double humidity = main["humidity"];
JsonObject weather = doc["weather"][0];
String description = weather["description"];
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C, Humidity: ");
Serial.print(humidity);
Serial.print(" %, Description: ");
Serial.println(description);
delay(60000); // Wait for 1 minute before checking again
}
```
该代码使用 ESP8266 连接到 OpenWeatherMap API,获取指定城市的天气信息,并将温度、湿度和天气描述打印到串口监视器中。你需要替换 `your_SSID`、`your_PASSWORD` 和 `your_API_KEY` 为你的 WiFi 名称、密码和 OpenWeatherMap API 密钥。同时你可以修改 `city` 变量以获取其他城市的天气信息。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)