当前位置:网站首页>JSON parsing, esp32 easy access to time, temperature and weather
JSON parsing, esp32 easy access to time, temperature and weather
2022-06-27 00:52:00 【arenascat】
Preface
play ESP You will need to get all kinds of information on the network , The content of getting started is to get the network time , By connecting NTP Server to complete .
Another home is to get the temperature and weather , It is usually used for clock items .
Here is the simplest way to get , And how to analyze it conveniently and quickly JSON
Used header files and functions
#include <Thread.h> // Multithreading
#include <U8g2lib.h> //U8glib, A well-known drawing library
#include <Wire.h> //I2C Correlation function
#include <WiFi.h> //ESP32 Wifi Correlation function
#include "time.h" // Time processing
#include <HTTPClient.h> // obtain http
#include <ArduinoJson.h> // analysis json
1. Connect to the network and time acquisition
All the basic is to connect to the network , Use here Wifi Connect , Because of the simplification, we first define ssid And password
const char *ssid = "wifi account number "; //
const char *password = "wifi Password ";
Then there is the definition ntp The server , When using Alibaba cloud servers, you should pay attention to the time offset of daylight saving time and time zone , We are Beijing time ,GMT+8 So is 28800
const char *ntpServer = "ntp.aliyun.com"; // Time server
const long gmtOffset_sec = 28800; // Time migration
const int daylightOffset_sec = 0;
And then it starts wifi, wait for wifi Connect , The connection function used here is Wifi.begin(), And then by judgment Wifi.status() Whether it is WL_CONNECTED To judge ESP32 Is it connected to the router at this time
Here I use a variable i To make a counter , achieve 127 Prompt error when , Can't connect to the Internet .
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(50);
Serial.print(".");
//u8g2.setCursor(2 + (i++), );
u8g2.drawLine(0, 0, (i++), 0);
u8g2.sendBuffer();
if (i == 127)
{
DisError();
}
}
If connected , Is to get time , Use configTime Function to complete
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
Finally, disconnect , close ESP32 Of Wifi The function achieves the purpose of saving power , Measured closing Wifi Just open OLED The power consumption is 20ma about .
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
The whole function is as follows
// Get online time
void getNetTime()
{
int i = 0;
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(50);
Serial.print(".");
//u8g2.setCursor(2 + (i++), );
u8g2.drawLine(0, 0, (i++), 0);
u8g2.sendBuffer();
if (i == 127)
{
Desirer();
}
}
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
u8g2.setDrawColor(1);
u8g2.setFont(font1);
u8g2.setCursor(10, 48);
clearHalf();
u8g2.setDrawColor(1);
u8g2.print("Get Time!"); //TODO Get the prompt of time
// u8g2.sendBuffer();
printLocalTime();
Serial.println(" CONNECTED");
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
}
Get the weather and JSON analysis
To get the weather, you need to connect Wifi Under the circumstances , The details are described in the previous chapter , Connecting to Wifi hotspot / In the case of routers , visit API, obtain JSON And analyze the weather and temperature , This is a ESP32 What to do in this chapter .
Because it is online , So you need to use dynamic JSON analysis , The library used here is AduinoJson, Use DynamicJsonDocument To initialize a store Json Data memory space
DynamicJsonDocument doc(2048);
We use the mind to know the weather , its api The format is as follows , You need to register your account and apply for API( Completely free ), How to apply is omitted in this article . You need to customize API Private key and your city .
String tagethttp = "https://api.seniverse.com/v3/weather/now.json?key= Here's your API Key &location= Fill in the phonetic name of the city here &language=en";
Here you need to instantiate a HTTPClient, And then use begin Function to try to connect
HTTPClient https;
https.begin(tagethttp);
complete https After connection , Here we need to describe ArduinoJson Usage of , For parsing we use API Acquired data
Get the weather directly Json The data looks like this :
{"results":[{"location":{"id":"WX4FBXXFKE4F","name":"Beijing","country":"CN","path":"Beijing,Beijing,China","timezone":"Asia/Shanghai","timezone_offset":"+08:00"},"now":{"text":"Overcast","code":"9","temperature":"26"},"last_update":"2021-08-11T21:24:24+08:00"}]}
After the browser is optimized, it can be seen that it is a multi-layer structure , It is divided into location and now
ArduinoJson It can help us parse data quickly and simply , It is in the form of layer upon layer analysis , First get Json data , This is the string
String payload = https.getString();
After that, it needs to be resolved to Json, Stored in the partition just now DynamicJsonDocument Storage space
deserializeJson(doc, payload);
The next step is to use JsonObject To get the whole Json In the data ,now That part
JsonObject results_0 = doc["results"][0];
JsonObject results_0_now = results_0["now"];
Next, get the weather
weather = results_0_now["text"];
And the temperature
temperature = results_0_now["temperature"];
This completes all the parsing .
Get the whole weather and temperature , analysis JSON The code is as follows , I use U8G2 To achieve OLED Show :
int temperature = 0;
const char *weather;
void getHttp() //TODO obtain http Webpage
{
DynamicJsonDocument doc(2048);
HTTPClient https;
https.begin(tagethttp);
int httpCode = https.GET();
u8g2.setFont(font1);
u8g2.clear();
u8g2.setCursor(3, 50);
if (httpCode > 0)
{
u8g2.sendBuffer();
String payload = https.getString();
deserializeJson(doc, payload);
JsonObject results_0 = doc["results"][0];
JsonObject results_0_now = results_0["now"];
weather = results_0_now["text"];
temperature = results_0_now["temperature"];
}
else
{
u8g2.print("Get http Failed");
u8g2.sendBuffer();
delay(1000);
}
}
More tools
Here is also a method , Is to use online tools to quickly preview the data you get , And screening their results
https://wandbox.org/permlink/hcB7LwkuBtcUc3u6
Write some code here , You can view the final output directly below , It is very fast and easy to use .
边栏推荐
- 解决u8glib只显示一行文字或者不显示的问题
- About Random Numbers
- 接口测试框架实战(一) | Requests 与接口请求构造
- redis详细教程
- 【Vscode】预览md文件
- These 10 copywriting artifacts help you speed up the code. Are you still worried that you can't write a copywriting for US media?
- How to control the quality of HD slip ring in the production process
- 寻找旋转排序数组中的最小值 II[经典抽象二分 + 如何破局左中右三者相等]
- 光谱共焦如何测量玻璃基板厚度
- Oracle 數據庫基本知識概念
猜你喜欢
随机推荐
How do new investors open accounts online? Is it safe to open accounts online and speculate in stocks
目前哪个证券公司炒股开户是最好最安全的?
Oracle 数据库基本知识概念
LeetCode 142. Circular linked list II
如何写好测试用例以及go单元测试工具testify简单介绍
Gaussian and Summary Stats
[vscade] preview MD file
Lambda expression
Oracle database basics concepts
Freescale 单片机概述
Concepts de base de données Oracle
Simple and fast digital network (network dolls in the network)
Sword finger offer 10- ii Frog jumping on steps
2022年地理信息系统与遥感专业就业前景与升学高校排名选择
基于SSMP的宠物医院管理系统
matlab数据类型 —— 字符型
Flink practical problems (VII): no watermark (watermarks are only available eventtime is used)
如何通俗易懂的描述机器学习的流程?
统一结果集的封装
Is it safe for CITIC Securities Commission to open an online account and speculate in stocks