前言
本文的目的是为了给将要制作的ESP32手环做技术储备
记录通过心知天气API获取天气数据
硬件准备
- ESP-WROOM-32E开发板
软件准备
- VSCODE+PlatformIO
相关链接
https://blog.csdn.net/weixin_42487906/article/details/113767644
在我之前的文章里,实现了用art-pi rtt的websocket软件包调用心知天气的API获取到天气信息
在进行本文内容前,需要根据上文,先注册一个心知天气的账户,申请免费的产品,调用免费的API
上图是通过调用这个API,获得的天气信息,是Json格式的,所以在ESP32上,采用ArduinoJson来处理Json格式的信息
代码编写
代码比较简单,很容易看懂,重要的是要把下面的privatekey换成你自己注册的心知天气的私钥,然后ssid和password换成你自己wifi的wifi名和密码
#include <Arduino.h>
#include <ArduinoJson.h>
#include <WiFi.h>const char *ssid = "XXXXX";
const char *password = "XXXXXXX";const char *host = "api.seniverse.com";
const char *privateKey = "XXXXXXXXXX";
const char *city = "wuhan";
const char *language = "en";struct WetherData
{char city[32];char weather[64];char high[32];char low[32];char humi[32];
};void setup()
{// put your setup code here, to run once:Serial.begin(115200);Serial.print("Connecting to ");Serial.println(ssid);WiFi.begin(ssid, password);while (WiFi.status() != WL_CONNECTED){delay(500);Serial.print(".");}Serial.println("");Serial.println("WiFi connected");Serial.println("IP address: ");Serial.println(WiFi.localIP());Serial.println("");Serial.println("WiFi Conected!");WiFiClient client;if (!client.connect(host, 80)){Serial.println("Connect host failed!");return;}Serial.println("host Conected!");String getUrl = "/v3/weather/daily.json?key=";getUrl += privateKey;getUrl += "&location=";getUrl += city;getUrl += "&language=";getUrl += language;client.print(String("GET ") + getUrl + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");Serial.println("Get send");char endOfHeaders[] = "\r\n\r\n";bool ok = client.find(endOfHeaders);if (!ok){Serial.println("No response or invalid response!");}Serial.println("Skip headers");String line="";line += client.readStringUntil('\n'); Serial.println(line);DynamicJsonDocument doc(1400);DeserializationError error = deserializeJson(doc, line);if (error){Serial.println("deserialize json failed");return;}Serial.println("deserialize json success");struct WetherData weatherdata = {0};strcpy(weatherdata.city, doc["results"][0]["location"]["name"].as<const char*>());strcpy(weatherdata.weather, doc["results"][0]["daily"][0]["text_day"].as<const char*>());strcpy(weatherdata.high, doc["results"][0]["daily"][0]["high"].as<const char*>());strcpy(weatherdata.low, doc["results"][0]["daily"][0]["low"].as<const char*>());strcpy(weatherdata.humi, doc["results"][0]["daily"][0]["humidity"].as<const char*>());Serial.println("City");Serial.println(weatherdata.city);Serial.println("textDay");Serial.println(weatherdata.weather);Serial.println("temp high");Serial.println(weatherdata.high);Serial.println("temp low");Serial.println(weatherdata.low);Serial.println("humi");Serial.println(weatherdata.humi);Serial.println("read json success");Serial.println();Serial.println("closing connection");client.stop();
}void loop()
{// put your main code here, to run repeatedly:
}