arduino获取天气
时间: 2025-07-04 11:57:10 浏览: 9
### 如何使用 Arduino 获取天气数据
为了利用 Arduino 设备获取天气信息,可以采用 HTTP 请求的方式连接至提供此类信息服务的应用程序接口(API),并解析返回的数据。对于 ESP8266 或 ESP32 这样的 Wi-Fi 功能模块而言,这变得尤为简单。
下面是一个基于 ESP8266 并结合和风天气 API 来获取天气信息的例子:
#### 准备工作
- 安装必要的库文件,如 `ESP8266WiFi`、`ESP8266HTTPClient` 和 `ArduinoJson`。
- 注册和风天气账号以获得个人专属的 API Key[^3]。
#### 示例代码
```cpp
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// 替换成自己的API key以及城市ID或名称
#define WEATHER_API_KEY "your_api_key"
#define LOCATION "beijing"
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 WiFi network");
}
void loop() {
if(WiFi.status()== WL_CONNECTED){
String url = "https://free-api.heweather.net/s6/weather/now?location=" + String(LOCATION) +"&key="+String(WEATHER_API_KEY);
if (HTTPClient http) {
http.begin(url); // Specify destination for HTTP request
int httpResponseCode = http.GET();
if(httpResponseCode>0){
String payload = http.getString();
DynamicJsonDocument doc(1024);
deserializeJson(doc, payload);
JsonObject nowObj = doc["HeWeather6"][0]["now"];
const char* tmp = nowObj["tmp"];
const char* cond_txt = nowObj["cond_txt"];
Serial.print("Temperature: ");
Serial.println(tmp);
Serial.print("Condition Text: ");
Serial.println(cond_txt);
}
http.end(); // Close connection
}
delay(60000); // Wait a minute before sending another request.
}
}
```
此段代码实现了每分钟向指定的城市发起一次当前天气状况请求,并打印温度与描述文字到串口监视器上。
阅读全文
相关推荐


















