ESP32s3联网访问天气api并打印出来
时间: 2024-03-26 22:14:42 浏览: 148
以下是ESP32s3联网访问天气API并打印出来的示例代码:
```c++
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* weather_api_key = "your_API_key";
const char* weather_api_url = "http://api.openweathermap.org/data/2.5/weather?q=Shanghai&appid=";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("WiFi connected!");
String url = String(weather_api_url) + String(weather_api_key);
HTTPClient http;
http.begin(url);
int httpCode = http.GET();
if (httpCode > 0) {
String payload = http.getString();
Serial.println(payload);
DynamicJsonDocument doc(1024);
deserializeJson(doc, payload);
JsonObject main = doc["main"];
float temp = main["temp"];
float feels_like = main["feels_like"];
float temp_min = main["temp_min"];
float temp_max = main["temp_max"];
Serial.println("Temperature: " + String(temp) + " K");
Serial.println("Feels like: " + String(feels_like) + " K");
Serial.println("Maximum temperature: " + String(temp_max) + " K");
Serial.println("Minimum temperature: " + String(temp_min) + " K");
}
http.end();
}
void loop() {
}
```
在此示例中,我们首先连接到WiFi网络,然后使用HTTPClient库访问OpenWeatherMap API获取当前上海的天气信息。我们使用ArduinoJson库解析返回的JSON响应,并打印出温度、最高温度、最低温度和体感温度。
请注意,您需要替换示例代码中的ssid、password和weather_api_key变量值,以便它们与您的网络和API密钥匹配。
阅读全文