写一个ESP8266获取天气的函数
时间: 2024-05-01 12:17:01 浏览: 196
以下是一个基于ESP8266的获取天气的函数示例:
```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 int httpsPort = 443;
const char* fingerprint = "your_SSL_FINGERPRINT";
void setup() {
Serial.begin(115200);
delay(10);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
WiFiClientSecure client;
client.setFingerprint(fingerprint);
if (!client.connect(host, httpsPort)) {
Serial.println("connection failed");
return;
}
String url = "/data/2.5/weather?q=London,uk&appid=your_APPID";
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
while (client.connected()) {
String line = client.readStringUntil('\n');
if (line == "\r") {
break;
}
}
String response = "";
while (client.available()) {
response += client.readString();
}
const size_t bufferSize = JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(6) + JSON_OBJECT_SIZE(8) + JSON_OBJECT_SIZE(11) + JSON_OBJECT_SIZE(12) + JSON_OBJECT_SIZE(13) + JSON_OBJECT_SIZE(14) + JSON_OBJECT_SIZE(15) + 400;
DynamicJsonBuffer jsonBuffer(bufferSize);
JsonObject& root = jsonBuffer.parseObject(response);
if (!root.success()) {
Serial.println("parseObject() failed");
return;
}
const char* cityName = root["name"];
float temperature = root["main"]["temp"];
const char* description = root["weather"][0]["description"];
Serial.print("City: ");
Serial.println(cityName);
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
Serial.print("Description: ");
Serial.println(description);
}
delay(60000); // 1 minute
}
```
这个函数使用ESP8266连接到OpenWeatherMap API,并获取伦敦的天气信息。你需要将 `your_SSID`,`your_PASSWORD`,`your_SSL_FINGERPRINT` 和 `your_APPID` 替换为你自己的 WiFi 和 OpenWeatherMap API 的访问信息。
该函数使用 `WiFiClientSecure` 连接到 API,以确保安全连接。然后,它构建一个 URL,并发送一个 GET 请求。一旦收到响应,它使用 ArduinoJson 库解析 JSON 数据,并提取城市名称、温度和天气描述。最后,它打印这些信息到串口监视器。
该函数每分钟执行一次,以获取最新的天气信息。你可以根据自己的需要更改这个频率。
阅读全文