数码之家

 找回密码
 立即注册

QQ登录

只需一步,快速开始

微信登录

微信扫一扫,快速登录

搜索
查看: 183|回复: 0

[STM] 【零知ESP8266教程】快速入门19 使用NTP服务器获取网络时间

[复制链接]
发表于 2019-11-2 14:37:34 | 显示全部楼层 |阅读模式

马上注册,认识更多玩家好友,查阅更多资源,享有更多功能

您需要 登录 才可以下载或查看,没有帐号?立即注册 微信登录

x

上次的分享,我们获取了一枚天气信息,但是呢,信息最重要的属性之一就是时效性,如何去确认我们信息的时效性呢,简单,保持自己时间的准确喽。

Time is valuable thing!

时间对我们是很重要的。通常,我们需要进行时间校准(PS:在很多时候,你细心留意就发现时间是错误的),一般就可以用NTP服务器进行获取时间信息,下面使用零知-ESP8266上进行NTP时间的获取。

一、硬件
电脑,windows系统
零知ESP8266开发板
micro-usb线
二、
(1)打开零知开源开发软件,选择零知ESP8266开发板,界面如图所示:

1.png

(2)电脑连接零知ESP8266开发板

3.png

(3)烧写程序:
①可以直接选择软件中的示例程序

2.png

②也可以上传以下代码:

  1. /*
  2. * TimeNTP_ESP8266WiFi.ino
  3. * Example showing time sync to NTP time source
  4. *
  5. * This sketch uses the ESP8266WiFi library
  6. */
  7.   
  8. #include <TimeLib.h>
  9. #include <ESP8266WiFi.h>
  10. #include <WiFiUdp.h>
  11.   
  12. const char ssid[] = "xx";  //  your network SSID (name)
  13. const char pass[] = "xx";       // your network password
  14.   
  15. // NTP Servers:
  16. static const char ntpServerName[] = "cn.ntp.org.cn";
  17. //static const char ntpServerName[] = "time.nist.gov";
  18. //static const char ntpServerName[] = "time-a.timefreq.bldrdoc.gov";
  19. //static const char ntpServerName[] = "time-b.timefreq.bldrdoc.gov";
  20. //static const char ntpServerName[] = "time-c.timefreq.bldrdoc.gov";
  21.   
  22. const int timeZone = 8; //BeiJing in China
  23.   
  24. // const int timeZone = 1;     // Central European Time
  25. //const int timeZone = -5;  // Eastern Standard Time (USA)
  26. //const int timeZone = -4;  // Eastern Daylight Time (USA)
  27. //const int timeZone = -8;  // Pacific Standard Time (USA)
  28. //const int timeZone = -7;  // Pacific Daylight Time (USA)
  29.   
  30.   
  31. WiFiUDP Udp;
  32. unsigned int localPort = 8888;  // local port to listen for UDP packets
  33.   
  34. time_t getNtpTime();
  35. void digitalClockDisplay();
  36. void printDigits(int digits);
  37. void sendNTPpacket(IPAddress &address);
  38.   
  39. void setup()
  40. {
  41.   Serial.begin(9600);
  42.   while (!Serial) ; // Needed for Leonardo only
  43.   delay(250);
  44.   Serial.println("TimeNTP Example");
  45.   Serial.print("Connecting to ");
  46.   Serial.println(ssid);
  47.   WiFi.begin(ssid, pass);
  48.   
  49.   while (WiFi.status() != WL_CONNECTED) {
  50.     delay(500);
  51.     Serial.print(".");
  52.   }
  53.   
  54.   Serial.print("IP number assigned by DHCP is ");
  55.   Serial.println(WiFi.localIP());
  56.   Serial.println("Starting UDP");
  57.   Udp.begin(localPort);
  58.   Serial.print("Local port: ");
  59.   Serial.println(Udp.localPort());
  60.   Serial.println("waiting for sync");
  61.   setSyncProvider(getNtpTime);
  62.   setSyncInterval(300);
  63. }
  64.   
  65. time_t prevDisplay = 0; // when the digital clock was displayed
  66.   
  67. void loop()
  68. {
  69.   if (timeStatus() != timeNotSet) {
  70.     if (now() != prevDisplay) { //update the display only if time has changed
  71.       prevDisplay = now();
  72.       digitalClockDisplay();
  73.     }
  74.   }
  75. }
  76.   
  77. void digitalClockDisplay()
  78. {
  79.   // digital clock display of the time
  80.   Serial.print(hour());
  81.   printDigits(minute());
  82.   printDigits(second());
  83.   Serial.print(" ");
  84.   Serial.print(day());
  85.   Serial.print(".");
  86.   Serial.print(month());
  87.   Serial.print(".");
  88.   Serial.print(year());
  89.   Serial.println();
  90. }
  91.   
  92. void printDigits(int digits)
  93. {
  94.   // utility for digital clock display: prints preceding colon and leading 0
  95.   Serial.print(":");
  96.   if (digits < 10)
  97.     Serial.print('0');
  98.   Serial.print(digits);
  99. }
  100.   
  101. /*-------- NTP code ----------*/
  102.   
  103. const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
  104. byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets
  105.   
  106. time_t getNtpTime()
  107. {
  108.   IPAddress ntpServerIP; // NTP server's ip address
  109.   
  110.   while (Udp.parsePacket() > 0) ; // discard any previously received packets
  111.   Serial.println("Transmit NTP Request");
  112.   // get a random server from the pool
  113.   WiFi.hostByName(ntpServerName, ntpServerIP);
  114.   Serial.print(ntpServerName);
  115.   Serial.print(": ");
  116.   Serial.println(ntpServerIP);
  117.   sendNTPpacket(ntpServerIP);
  118.   uint32_t beginWait = millis();
  119.   while (millis() - beginWait < 1500) {
  120.     int size = Udp.parsePacket();
  121.     if (size >= NTP_PACKET_SIZE) {
  122.       Serial.println("Receive NTP Response");
  123.       Udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
  124.       unsigned long secsSince1900;
  125.       // convert four bytes starting at location 40 to a long integer
  126.       secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
  127.       secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
  128.       secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
  129.       secsSince1900 |= (unsigned long)packetBuffer[43];
  130.       return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
  131.     }
  132.   }
  133.   Serial.println("No NTP Response :-(");
  134.   return 0; // return 0 if unable to get the time
  135. }
  136.   
  137. // send an NTP request to the time server at the given address
  138. void sendNTPpacket(IPAddress &address)
  139. {
  140.   // set all bytes in the buffer to 0
  141.   memset(packetBuffer, 0, NTP_PACKET_SIZE);
  142.   // Initialize values needed to form NTP request
  143.   // (see URL above for details on the packets)
  144.   packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  145.   packetBuffer[1] = 0;     // Stratum, or type of clock
  146.   packetBuffer[2] = 6;     // Polling Interval
  147.   packetBuffer[3] = 0xEC;  // Peer Clock Precision
  148.   // 8 bytes of zero for Root Delay & Root Dispersion
  149.   packetBuffer[12] = 49;
  150.   packetBuffer[13] = 0x4E;
  151.   packetBuffer[14] = 49;
  152.   packetBuffer[15] = 52;
  153.   // all NTP fields have been given values, now
  154.   // you can send a packet requesting a timestamp:
  155.   Udp.beginPacket(address, 123); //NTP requests are to port 123
  156.   Udp.write(packetBuffer, NTP_PACKET_SIZE);
  157.   Udp.endPacket();
  158. }
复制代码

然后验证,并且上传到开发板。

四、结果

4.png

然后对照自己的时间:

5.jpg

赶紧动手检查看看自己的时间对不对呢?
我先校准自己的。

顺便问你们一句:有没有发现自己的时间变快了呢?(细思极恐)


您需要登录后才可以回帖 登录 | 立即注册 微信登录

本版积分规则

Archiver|手机版|小黑屋|关于我们|联系我们|网站条款|数码之家 ( 闽ICP备05031405号 )

GMT+8, 2019-12-12 00:13 , Processed in 0.170799 second(s), 17 queries , MemCache On.

Powered by Discuz!

© 2001-2019 Comsenz Inc.

快速回复 返回顶部 返回列表