当前位置:网站首页>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 .

原网站

版权声明
本文为[arenascat]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/178/202206270009550116.html