Advertisement
Guest User

ESP8266 + TM1637 NTP clock

a guest
Apr 29th, 2019
397
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 6.80 KB | None | 0 0
  1. /* Udp NTP Client Get the time from a Network Time Protocol (NTP) time server
  2. Demonstrates use of UDP sendPacket and ReceivePacket For more on NTP time servers
  3. and the messages needed to communicate with them, see http://en.wikipedia.org/wiki/Network_Time_Protocol
  4. created 4 Sep 2010 by Michael Margolis modified 9 Apr 2012 by Tom Igoe updated for the ESP8266 12 Apr 2015
  5. by Ivan Grokhotkov This code is in the public domain.
  6.  
  7. CH_PD, RESET, GPIO0, GPIO2 подтягивают резисторами 10k к VCC модуля esp8266
  8. */
  9.  
  10. #include <ESP8266WiFi.h>
  11. #include <WiFiUdp.h>
  12. #include "TM1637.h"
  13. #include <Ticker.h>
  14.  
  15. Ticker flipper;
  16. TM1637 tm1637(0, 2);              // CLK - 0, DIO - 2 (D6, D5)
  17.  
  18. #define GMT 3                       // часовой пояс
  19. #define brightness 7               // яркость, от 0 до 7
  20.  
  21. char ssid[] = "network_name";        //  your network SSID (name)
  22. char pass[] = "network_pass";        // your network password
  23.  
  24. byte hour, minute, second;
  25. boolean point;
  26.  
  27. unsigned int localPort = 2390;      // local port to listen for UDP packets
  28.  
  29. /* Don't hardwire the IP address or we won't get the benefits of the pool. *  Lookup the IP address for the host name instead */
  30. //IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server
  31. IPAddress timeServerIP; // time.nist.gov NTP server address
  32. const char* ntpServerName = "time.nist.gov";
  33.  
  34. const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message
  35.  
  36. byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets
  37.  
  38. // A UDP instance to let us send and receive packets over UDP
  39. WiFiUDP udp;
  40.  
  41. void setup()
  42. {
  43.   Serial.begin(115200);
  44.    
  45.   tm1637.init();                      ///tm1637
  46.   tm1637.set(brightness);
  47.  
  48.   flipper.attach(1, flip);          /// прерывание 1 сек
  49.  
  50.   Serial.println();
  51.   Serial.println();
  52.  
  53.   // We start by connecting to a WiFi network
  54.   Serial.print("Connecting to ");
  55.   Serial.println(ssid);
  56.   WiFi.begin(ssid, pass);
  57.  
  58.   while (WiFi.status() != WL_CONNECTED) {
  59.     delay(500);
  60.     Serial.print(".");
  61.   }
  62.   Serial.println("");
  63.  
  64.   Serial.println("WiFi connected");
  65.   Serial.println("IP address: ");
  66.   Serial.println(WiFi.localIP());
  67.  
  68.   Serial.println("Starting UDP");
  69.   udp.begin(localPort);
  70.   Serial.print("Local port: ");
  71.   Serial.println(udp.localPort());
  72.  
  73.   oldloop();        /// синхронизируем время при включении
  74. }
  75.  
  76. void loop(){
  77.   if (second == 30){            // если насчитали 30 сек
  78.     flipper.detach();           // выключаем прерывание
  79.     delay(1500);                // ждем, чтобы повторно не запустить
  80.     oldloop();                  // синхронизируем время
  81.     flipper.attach(1, flip);    // запускаем прерывание
  82.   }
  83.  
  84.    int8_t TimeDisp[4];          // отправляем всё на экран
  85.    tm1637.point(point);         // управление :, мигаем если запущено прерывание
  86.    
  87.    TimeDisp[0] = hour / 10;
  88.    TimeDisp[1] = hour % 10;
  89.    TimeDisp[2] = minute  / 10;
  90.    TimeDisp[3] = minute  % 10;  
  91.    tm1637.display(TimeDisp);
  92. }
  93.  
  94. void oldloop()
  95. {
  96.   //get a random server from the pool
  97.   WiFi.hostByName(ntpServerName, timeServerIP);
  98.  
  99.   sendNTPpacket(timeServerIP); // send an NTP packet to a time server
  100.   // wait to see if a reply is available
  101.   delay(1000);
  102.  
  103.   int cb = udp.parsePacket();
  104.   if (!cb) {
  105.     Serial.println("no packet yet");
  106.   }
  107.   else {
  108.     Serial.print("packet received, length=");
  109.     Serial.println(cb);
  110.     // We've received a packet, read the data from it
  111.     udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
  112.  
  113.     //the timestamp starts at byte 40 of the received packet and is four bytes,
  114.     // or two words, long. First, esxtract the two words:
  115.  
  116.     unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
  117.     unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
  118.     // combine the four bytes (two words) into a long integer
  119.     // this is NTP time (seconds since Jan 1 1900):
  120.     unsigned long secsSince1900 = highWord << 16 | lowWord;
  121.     Serial.print("Seconds since Jan 1 1900 = " );
  122.     Serial.println(secsSince1900);
  123.  
  124.     // now convert NTP time into everyday time:
  125.     Serial.print("Unix time = ");
  126.     // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
  127.     const unsigned long seventyYears = 2208988800UL;
  128.     // subtract seventy years:
  129.     unsigned long epoch = secsSince1900 - seventyYears;
  130.     // print Unix time:
  131.     Serial.println(epoch);
  132.    
  133.           /// корректировка часового пояса и синхронизация
  134.     epoch = epoch + GMT * 3600;    
  135.    
  136.     hour = (epoch  % 86400L) / 3600;
  137.     minute = (epoch  % 3600) / 60;
  138.     second = epoch % 60;
  139.    
  140.  
  141.     // print the hour, minute and second:
  142.     Serial.print("The UTC time is ");       // UTC is the time at Greenwich Meridian (GMT)
  143.     Serial.print((epoch  % 86400L) / 3600); // print the hour (86400 equals secs per day)
  144.     Serial.print(':');
  145.     if ( ((epoch % 3600) / 60) < 10 ) {
  146.       // In the first 10 minutes of each hour, we'll want a leading '0'
  147.       Serial.print('0');
  148.     }
  149.     Serial.print((epoch  % 3600) / 60); // print the minute (3600 equals secs per minute)
  150.     Serial.print(':');
  151.     if ( (epoch % 60) < 10 ) {
  152.       // In the first 10 seconds of each minute, we'll want a leading '0'
  153.       Serial.print('0');
  154.     }
  155.     Serial.println(epoch % 60); // print the second
  156.   }
  157.   // wait ten seconds before asking for the time again
  158.  
  159.  
  160. }
  161.  
  162. // send an NTP request to the time server at the given address
  163. unsigned long sendNTPpacket(IPAddress& address)
  164. {
  165.   Serial.println("sending NTP packet...");
  166.   // set all bytes in the buffer to 0
  167.   memset(packetBuffer, 0, NTP_PACKET_SIZE);
  168.   // Initialize values needed to form NTP request
  169.   // (see URL above for details on the packets)
  170.   packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  171.   packetBuffer[1] = 0;     // Stratum, or type of clock
  172.   packetBuffer[2] = 6;     // Polling Interval
  173.   packetBuffer[3] = 0xEC;  // Peer Clock Precision
  174.   // 8 bytes of zero for Root Delay & Root Dispersion
  175.   packetBuffer[12]  = 49;
  176.   packetBuffer[13]  = 0x4E;
  177.   packetBuffer[14]  = 49;
  178.   packetBuffer[15]  = 52;
  179.  
  180.   // all NTP fields have been given values, now
  181.   // you can send a packet requesting a timestamp:
  182.   udp.beginPacket(address, 123); //NTP requests are to port 123
  183.   udp.write(packetBuffer, NTP_PACKET_SIZE);
  184.   udp.endPacket();
  185. }
  186.  
  187.  
  188. void flip(){
  189.   point = !point;
  190.   second++;
  191.   if (second > 59){
  192.     second = 0;
  193.     minute++;      
  194.   }
  195.   if (minute > 59){
  196.     minute = 0;
  197.     hour++;  
  198.   }
  199.   if (hour > 23){
  200.     hour = 0;
  201.   }
  202.  
  203. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement