UdpNTPClient.ino 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. /*
  2. WiFiEsp example: UdpNTPClient
  3. Get the time from a Network Time Protocol (NTP) time server.
  4. Demonstrates use of UDP to send and receive data packets
  5. For more on NTP time servers and the messages needed to communicate with them,
  6. see http://en.wikipedia.org/wiki/Network_Time_Protocol
  7. NOTE: The serial buffer size must be larger than 36 + packet size
  8. In this example we use an UDP packet of 48 bytes so the buffer must be
  9. at least 36+48=84 bytes that exceeds the default buffer size (64).
  10. You must modify the serial buffer size to 128
  11. For HardwareSerial modify _SS_MAX_RX_BUFF in
  12. Arduino\hardware\arduino\avr\cores\arduino\SoftwareSerial.h
  13. For SoftwareSerial modify _SS_MAX_RX_BUFF in
  14. Arduino\hardware\arduino\avr\libraries\SoftwareSerial\SoftwareSerial.h
  15. */
  16. #include "WiFiEsp.h"
  17. #include "WiFiEspUdp.h"
  18. // Emulate Serial1 on pins 6/7 if not present
  19. #ifndef HAVE_HWSERIAL1
  20. #include "SoftwareSerial.h"
  21. SoftwareSerial Serial1(6, 7); // RX, TX
  22. #endif
  23. char ssid[] = "Twim"; // your network SSID (name)
  24. char pass[] = "12345678"; // your network password
  25. int status = WL_IDLE_STATUS; // the Wifi radio's status
  26. char timeServer[] = "time.nist.gov"; // NTP server
  27. unsigned int localPort = 2390; // local port to listen for UDP packets
  28. const int NTP_PACKET_SIZE = 48; // NTP timestamp is in the first 48 bytes of the message
  29. const int UDP_TIMEOUT = 2000; // timeout in miliseconds to wait for an UDP packet to arrive
  30. byte packetBuffer[NTP_PACKET_SIZE]; // buffer to hold incoming and outgoing packets
  31. // A UDP instance to let us send and receive packets over UDP
  32. WiFiEspUDP Udp;
  33. void setup()
  34. {
  35. // initialize serial for debugging
  36. Serial.begin(115200);
  37. // initialize serial for ESP module
  38. Serial1.begin(9600);
  39. // initialize ESP module
  40. WiFi.init(&Serial1);
  41. // check for the presence of the shield
  42. if (WiFi.status() == WL_NO_SHIELD) {
  43. Serial.println("WiFi shield not present");
  44. // don't continue
  45. while (true);
  46. }
  47. // attempt to connect to WiFi network
  48. while ( status != WL_CONNECTED) {
  49. Serial.print("Attempting to connect to WPA SSID: ");
  50. Serial.println(ssid);
  51. // Connect to WPA/WPA2 network
  52. status = WiFi.begin(ssid, pass);
  53. }
  54. // you're connected now, so print out the data
  55. Serial.println("You're connected to the network");
  56. Udp.begin(localPort);
  57. }
  58. void loop()
  59. {
  60. sendNTPpacket(timeServer); // send an NTP packet to a time server
  61. // wait for a reply for UDP_TIMEOUT miliseconds
  62. unsigned long startMs = millis();
  63. while (!Udp.available() && (millis() - startMs) < UDP_TIMEOUT) {}
  64. Serial.println(Udp.parsePacket());
  65. if (Udp.parsePacket()) {
  66. Serial.println("packet received");
  67. // We've received a packet, read the data from it into the buffer
  68. Udp.read(packetBuffer, NTP_PACKET_SIZE);
  69. // the timestamp starts at byte 40 of the received packet and is four bytes,
  70. // or two words, long. First, esxtract the two words:
  71. unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
  72. unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
  73. // combine the four bytes (two words) into a long integer
  74. // this is NTP time (seconds since Jan 1 1900):
  75. unsigned long secsSince1900 = highWord << 16 | lowWord;
  76. Serial.print("Seconds since Jan 1 1900 = ");
  77. Serial.println(secsSince1900);
  78. // now convert NTP time into everyday time:
  79. Serial.print("Unix time = ");
  80. // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
  81. const unsigned long seventyYears = 2208988800UL;
  82. // subtract seventy years:
  83. unsigned long epoch = secsSince1900 - seventyYears;
  84. // print Unix time:
  85. Serial.println(epoch);
  86. // print the hour, minute and second:
  87. Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT)
  88. Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day)
  89. Serial.print(':');
  90. if (((epoch % 3600) / 60) < 10) {
  91. // In the first 10 minutes of each hour, we'll want a leading '0'
  92. Serial.print('0');
  93. }
  94. Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute)
  95. Serial.print(':');
  96. if ((epoch % 60) < 10) {
  97. // In the first 10 seconds of each minute, we'll want a leading '0'
  98. Serial.print('0');
  99. }
  100. Serial.println(epoch % 60); // print the second
  101. }
  102. // wait ten seconds before asking for the time again
  103. delay(10000);
  104. }
  105. // send an NTP request to the time server at the given address
  106. void sendNTPpacket(char *ntpSrv)
  107. {
  108. // set all bytes in the buffer to 0
  109. memset(packetBuffer, 0, NTP_PACKET_SIZE);
  110. // Initialize values needed to form NTP request
  111. // (see URL above for details on the packets)
  112. packetBuffer[0] = 0b11100011; // LI, Version, Mode
  113. packetBuffer[1] = 0; // Stratum, or type of clock
  114. packetBuffer[2] = 6; // Polling Interval
  115. packetBuffer[3] = 0xEC; // Peer Clock Precision
  116. // 8 bytes of zero for Root Delay & Root Dispersion
  117. packetBuffer[12] = 49;
  118. packetBuffer[13] = 0x4E;
  119. packetBuffer[14] = 49;
  120. packetBuffer[15] = 52;
  121. // all NTP fields have been given values, now
  122. // you can send a packet requesting a timestamp:
  123. Udp.beginPacket(ntpSrv, 123); //NTP requests are to port 123
  124. Udp.write(packetBuffer, NTP_PACKET_SIZE);
  125. Udp.endPacket();
  126. }