本站改版新增arduino频道
arduino 高德天气api
/* Arduino自带头文件 */
#include <WiFi.h>
/* Arduino自带头文件 */
#include <HTTPClient.h>
/* 需要下载的头文件 */
#include <ArduinoJson.h>
const char* ssid = "NBWIFI";
const char* password = "z7758521";
/* 将文档中的URL以及请求参数保存到变量中
注意删除"?parameters",以便填写请求参数 */
String url = "https://restapi.amap.com/v3/weather/weatherInfo?";
String adcode = "141081";
String key = "e43f5609a249f5e7075b5bee8a73bb7a";
String extensions = "base";
String output = "JSON";
/* 需要的响应数据 */
String province;
String city;
String weather;
String temperature;
void setup() {
Serial.begin(115200);
/* 开始连接WiFi */
Serial.begin(115200);
// 连接 WiFi
WiFi.begin(ssid, password);
Serial.print("正在连接 Wi-Fi");
// 检测是否连接成功
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("连接成功");
Serial.print("IP 地址:");
Serial.println(WiFi.localIP());
/* 创建 HTTPClient 对象 */
HTTPClient http;
/* 指定要发送请求的URL https://restapi.amap.com/v3/weather/weatherInfo?city=141081&key=e43f5609a249f5e7075b5bee8a73bb7a */
// http.begin(url+"city="+adcode+"&key="+key+"&extensions="+extensions+"&output="+output);
http.begin(url + "city=" + adcode + "&key=" + key);
/* GET请求,函数返回状态码 */
int http_code = http.GET();
Serial.println(http_code);
/* 获取响应数据的字符串格式 */
String response = http.getString();
Serial.println(response);
/* 关闭连接 */
http.end();
/* 创建 DynamicJsonDocument 对象 */
DynamicJsonDocument doc(1024);
/* 解析Json 数据 */
deserializeJson(doc, response);
// 用串口打印数据会发现lives是一个数组,[0]是数组下标
province = doc["lives"][0]["province"].as<String>(); //省份名
city = doc["lives"][0]["city"].as<String>(); //城市名
weather = doc["lives"][0]["weather"].as<String>(); //天气现象(汉字描述)
temperature = doc["lives"][0]["temperature"].as<String>(); //实时气温
winddirection = doc["lives"][0]["winddirection"].as<String>(); //风向
windpower = doc["lives"][0]["windpower"].as<String>(); //风级
humidity = doc["lives"][0]["humidity"].as<String>(); //空气湿度
Serial.println(province);
Serial.println(city);
Serial.println(weather);
Serial.println(temperature);
Serial.println(winddirection);
Serial.println(windpower);
Serial.println(humidity);
}
void loop() {}
Copyright © 2014 ESP56.com All Rights Reserved
晋ICP备14006235号-22 晋公网安备14108102001165号
执行时间: 0.009397029876709 seconds