当前位置:网站首页>Esp32 ultra detailed learning record: NTP synchronization time
Esp32 ultra detailed learning record: NTP synchronization time
2022-07-24 06:46:00 【Like warm know cold】

I originally wanted to find inspiration from open source projects , however ! That code sucks !!!!!
Open source projects inevitably copy code , Want to know NTP How to implement it? I have to read that pile of bad code , Bother !
Even if the open source project can ! No, it's the same bad ! generation ! code !
Find a way to see for yourself NTP How to implement the related Library of .
have access to aliyun Of NTP The server .
I found that many open source projects are used aliyun Of NTP The server .

What is? NTP
NTP:Network Time Protocol( Network time protocol )
️ NTP Is a protocol used to synchronize computer time in the network . Its purpose is to synchronize the computer's clock to universal coordinated time UTC.
UTC:Universal Time Coordinated( Coordinated universal time ) Based on the atomic time and second length .
GMT:Universal Time( World time ) Based on the rotation of the earth .
Beijing time adopts the district time of Dongba district as the standard time . Beijing time is faster than world time (UTC) Good morning! 8 Hours , Beijing time. =UTC+8.
Use NTPClient Library acquisition time
️ If you use NTPClient library , In fact, it's very simple, very simple !!
Just a few functions in the official routine are implemented ! Just four !
WiFiUDP ntpUDP; // establish UDP example
NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 60 * 60 * 8, 60000); //NTC
//UDP& udp, const char* poolServerName, long timeOffset, unsigned long updateInterval
// Initialization function
timeClient.begin();
// Acquisition time
timeClient.update();
timeClient.getFormattedTime();
such , You can get it directly Hours : minute : second The format of time .
Is like : Study ESP32 Still need to learn network protocol !
Functions to be explained :
NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 60 * 60 * 8, 60000); //NTC
//UDP& udp, const char* poolServerName, long timeOffset, unsigned long updateIntervalntpUDP:UDP example
"europe.pool.ntp.org":NTP Server address
60 * 60 * 8: It is the parameter needed to convert to the time of East 8th District : second * minute * Hours
60000: Update time
In the library interface , Only see the week 、 when 、 branch 、 Second interface ! No year 、 month 、 Japan .
#include <WiFi.h>
#include <WiFiUdp.h>
#include <NTPClient.h>
const char *ssid = "<SSID>";
const char *password = "<PASSWORD>";
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 3600, 60000);
void setup()
{
Serial.begin(115200);
WiFi.begin(ssid, password);
while ( WiFi.status() != WL_CONNECTED )
{
delay ( 500 );
Serial.print ( "." );
}
timeClient.begin();
}
void loop()
{
timeClient.update();
Serial.println(timeClient.getFormattedTime());
delay(1000);
}If you want to call this function similar to time interrupt every other period of time , Referential Ticker Library implements timer function .
ESP32 Core library functions
stay ESP32 Under the core folder of time.c file . Defined configTime Function is used to configure time . You don't need to reference the header file to call the function directly .
void configTime(long gmtOffset_sec, int daylightOffset_sec, const char* server1, const char* server2, const char* server3)- gmtOffset_sec: World time offset
- daylightOffset_sec: Time migration
- server: Server address
stay time.c In file , Other time setting functions are also provided , Including setting the time zone 、 Get the time zone and so on .
️ Get local time , Functions are also defined in time.c in , But using this function requires tm Type of structure storage time !
tm Is defined in C++ library time.h Structural body in .
struct tm - C++ Referencehttps://cplusplus.com/reference/ctime/tm/

struct tm
{
// The following are the regular dates
int tm_year; /* year , Its value is from 1900 Start */
int tm_mon; /* month ( From January on ,0 For January ) - The value range is [0,11] */
int tm_mday; /* The date of the month - The value range is [1,31] */
int tm_hour; /* when - The value range is [0,23] */
int tm_min; /* branch - The value range is [0,59] */
int tm_sec; /* second – The value range is [0,59] */
int tm_wday; /* week – The value range is [0,6], among 0 For Sunday ,1 On behalf of Monday , And so on */
int tm_yday; /* From the annual 1 month 1 The number of days the day begins – The value range is [0,365], among 0 representative 1 month 1 Japan ,1 representative 1 month 2 Japan , And so on */
int tm_isdst; /* Daylight saving time identifier , When daylight saving time is implemented ,tm_isdst Being positive . No daylight saving time ,tm_isdst by 0; When you don't know the situation ,tm_isdst() Negative .*/
long int tm_gmtoff; /* Specifies the time zone east of the date change line UTC Positive seconds in Eastern time zone or UTC Negative seconds in the Western time zone */
const char *tm_zone; /* The name of the current time zone ( And environment variables TZ of )*/
}; ️ If it's Chinese time , It should be noted that the year 、 The time of the month !
Example of function :
The function here refers to :Getting Date & Time From NTP Server With ESP32
#include "Arduino.h"
#include <WiFi.h>
#include "time.h" // In order to use tm Structure
const char* ssid = "<SSID>";
const char* password = "<PASSWORD>";
struct tm timeinfo;
void setup()
{
Serial.begin(115200);
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println(" CONNECTED");
configTime(60*60*8, 0, "ntp3.aliyun.com"); // Alibaba cloud servers
printLocalTime();
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
}
void loop()
{
struct tm timeinfo;
if(!getLocalTime(&timeinfo))
{
Serial.println("Failed to obtain time");
return;
}
Serial.println(&timeinfo, "%A, %Y-%m-%d %H:%M:%S");
delay(1000);
}Without incident , The following similar information will be printed on the serial port :
![]()
You can also read the structure , obtain
year = timeinfo.tm_year + 1900; // Year from 1900 Start
month = timeinfo.tm_mon + 1; // 0 Express 1 month
week = timeinfo.tm_wday; // Note here that this is the number returned , Not words !
...But this method cannot automatically update the time , It's a little annoying ! You can add Ticker To get the time for regular execution .
Don't use NTP The way to get time :API
In fact, it is similar to the previous article on knowing the weather Use the same method :
Know the weather conditions and get ,ESP32 Get weather information ( Including source code )_ Like warm know cold blog -CSDN Blog _esp32 Get weather ESP32 Get weather information https://blog.csdn.net/qq_41650023/article/details/124697234 I found several on the Internet API The interface of :
For example, knowing the weather API Back to JSON data :

The data returned by Suning :http://quan.suning.com/getSysTime.do
![]()
You can even check the website GET Request some websites API
For example, website : Now Beijing time Online standard Beijing time proofreading
Found on this website GET Request interface

The requested time can be found API That's it :https://www.beijing-time.org/t/time.asp
Request return value :
![]()
Some websites have API It's easier to find , Some are hard to find . Here is just an idea !
It's over at last ~
In fact, it's not difficult ~ !
After knowing it, I found NTP This kind of thing is in ESP32 for Arduino It's so easy to realize , I thought it was hard to realize before, and I was afraid for a long time !
This article is to provide an idea , The complete code of two implementation methods is attached , Tests are available ! If it is applied, there will be BUG, But that doesn't matter .
OK, If you are lucky enough to be seen by your friends , I hope it helped you .
Happy today ~ Learned the knowledge of heart ~
Will continue to update about ESP32 for Arduino Some small knowledge points of ~ Because I am also taking time to learn recently !
If this article brings you some help , Might as well spot individual Fabulous ~ Or is it spot spot Turn off notes !~
If you are the same beginner , It's not convenient to pay attention to this column ESP32 for Arduino Other articles of ~ They are all written for their own notes , I believe it will help you !

边栏推荐
- Batch implementation of key based authentication using sshpass
- Multiple types of functions
- Special effects - click the mouse and the randomly set text will appear
- kubernetes简介和架构及其原理
- Write blog at leisure ~ briefly talk about let, VaR and Const
- String问题
- JS - mouse and keyboard configuration and browser forbidden operation
- RAID configuration experiment
- Identification of Chinese medicinal materials
- Quick start of go language
猜你喜欢

Introduction, architecture and principle of kubernetes

【音频解码芯片】VS1503音频解码芯片的应用

Redis.conf详解

Talk about browser cache again

磁盘管理和文件系统

Explain the event cycle mechanism and differences between browser and node in detail

Kubernetes rapid installation

JSONObject按照key的A——Z顺序排序

Why can't index be the key of V-for?

Jenkins CI CD
随机推荐
RAID的配置实验
Secondary processing of template data
[lvgl (1)] a brief introduction to lvgl
PXE technology network installation
Transition effect
JS - mouse and keyboard configuration and browser forbidden operation
Quick start of go language
Go environment construction and start
Customize ZABBIX agent RPM package
【小型物体测速仪】只有原理,无代码
Redis特殊数据类型-HyperLogLog
【LVGL(重要)】样式属性API函数及其参数
创建WPF项目
adb交互-干掉难看的默认shell界面
Redis数据类型-String(字符串类型)
JS - calculate the side length and angle of a right triangle
Introduction to kubernetes (kubernetes benefits)
Redis基本类型-结合Set
DNS domain name resolution service
sql server 同步数据库 跨网段无公网ip几个常见小问题问题