esp32s3获取天气
时间: 2025-02-20 16:55:33 浏览: 64
### 使用ESP32S3从API获取实时天气数据
#### 准备工作
为了使ESP32S3能够连接互联网并访问在线服务,需确保设备已配置Wi-Fi设置。这通常涉及编写一段初始化网络连接的代码[^2]。
#### 获取API密钥
大多数气象信息服务提供商(如OpenWeatherMap, Weatherstack等)都要求注册账户来获得API Key。此Key用于身份验证请求,保证合法调用接口。
#### 编写Arduino代码实现功能
下面是一个简单的例子展示怎样利用HTTPClient库向特定URL发送GET请求,并解析返回JSON格式的结果:
```cpp
#include <WiFi.h>
#include "HTTPClient.h"
const char* ssid = "your_SSID"; // WiFi SSID
const char* password = "your_PASSWORD"; // WiFi Password
const char* host = "api.openweathermap.org";
String apiKey = "YOUR_API_KEY_HERE"; // Your API key from OpenWeatherMap or other service provider
float latitude = YOUR_LATITUDE; // Location's Latitude
float longitude = YOUR_LONGITUDE; // Location's Longitude
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 the Wi-Fi network");
}
void loop(){
if(WiFi.status()==WL_CONNECTED){
HTTPClient http;
String url = "http://" + String(host)+"/data/2.5/weather?lat="+String(latitude)+"&lon="+String(longitude)+"&appid="+apiKey;
http.begin(url.c_str());
int httpResponseCode = http.GET();
if(httpResponseCode>0){
String payload=http.getString();
Serial.println(payload);
DynamicJsonDocument doc(1024);
deserializeJson(doc,payload);
float temperature=doc["main"]["temp"]-273.15; //-273.15 converts Kelvin to Celsius.
int humidity=doc["main"]["humidity"];
Serial.print("Temperature:");
Serial.println(temperature);
Serial.print("Humidity:");
Serial.println(humidity);
}else{
Serial.print("Error on sending GET request: ");
Serial.println(httpResponseCode);
}
http.end();
}
}
```
这段程序首先建立了与指定SSID和密码对应的无线局域网之间的联系;接着构建了一个指向目标服务器的具体路径字符串`url`,其中包含了地理位置参数以及之前提到过的API密钥信息;最后通过发起一次标准HTTP GET方法调用来检索所需资源,并处理接收到的信息以提取温度和湿度数值[^3]。
阅读全文
相关推荐



















