你能写一段esp8266获取心知天气的代码吗
时间: 2024-03-14 22:46:24 浏览: 75
当然可以,以下是一个简单的示例代码:
```c++
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* host = "api.seniverse.com";
const String location = "your_location"; // 例如:"beijing" 或 "ip"
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 = "/v3/weather/now.json?key=" + apiKey + "&location=" + location;
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(1) + JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(6) + JSON_OBJECT_SIZE(7) + 260;
DynamicJsonDocument doc(capacity);
deserializeJson(doc, response);
JsonObject results = doc["results"][0];
JsonObject now = results["now"];
String text = now["text"];
int temperature = now["temperature"];
Serial.print("天气:");
Serial.print(text);
Serial.print(",温度:");
Serial.print(temperature);
Serial.println("℃");
delay(60000); // Wait for 1 minute before checking again
}
```
该代码使用 ESP8266 连接到心知天气 API,获取指定位置的天气信息,并将天气状况和温度打印到串口监视器中。你需要替换 `your_SSID`、`your_PASSWORD` 和 `your_API_KEY` 为你的 WiFi 名称、密码和心知天气 API 密钥。同时你可以修改 `location` 变量以获取其他位置的天气信息。
阅读全文