3 * Example showing time sync to NTP time source
5 * This sketch uses the Ethenet library with the user contributed UdpBytewise extension
10 #include <UdpBytewise.h> // UDP library from: bjoern@cs.stanford.edu 12/30/2008
11 #if UDP_TX_PACKET_MAX_SIZE <64 || UDP_RX_PACKET_MAX_SIZE < 64
12 #error : UDP packet size to small - modify UdpBytewise.h to set buffers to 64 bytes
16 * You may need to modify the UdpBytewise.h library to allow enough space in the buffers for the NTP packets.
17 * Open up UdpBytewse.h and set the following buffers to 64 bytes:
18 * #define UDP_TX_PACKET_MAX_SIZE 64
19 * #define UDP_RX_PACKET_MAX_SIZE 64
23 byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
24 byte ip[] = { 192, 168, 1, 44 }; // set the IP address to an unused address on your network
26 byte SNTP_server_IP[] = { 192, 43, 244, 18}; // time.nist.gov
27 //byte SNTP_server_IP[] = { 130,149,17,21}; // ntps1-0.cs.tu-berlin.de
28 //byte SNTP_server_IP[] = { 192,53,103,108}; // ptbtime1.ptb.de
31 time_t prevDisplay = 0; // when the digital clock was displayed
32 const long timeZoneOffset = 0L; // set this to the offset in seconds to your local time;
37 Ethernet.begin(mac,ip);
38 Serial.println("waiting for sync");
39 setSyncProvider(getNtpTime);
40 while(timeStatus()== timeNotSet)
41 ; // wait until the time is set by the sync provider
46 if( now() != prevDisplay) //update the display only if the time has changed
49 digitalClockDisplay();
53 void digitalClockDisplay(){
54 // digital clock display of the time
56 printDigits(minute());
57 printDigits(second());
61 Serial.print(month());
67 void printDigits(int digits){
68 // utility function for digital clock display: prints preceding colon and leading 0
75 /*-------- NTP code ----------*/
77 unsigned long getNtpTime()
79 sendNTPpacket(SNTP_server_IP);
81 if ( UdpBytewise.available() ) {
82 for(int i=0; i < 40; i++)
83 UdpBytewise.read(); // ignore every field except the time
84 const unsigned long seventy_years = 2208988800UL + timeZoneOffset;
85 return getUlong() - seventy_years;
87 return 0; // return 0 if unable to get the time
90 unsigned long sendNTPpacket(byte *address)
92 UdpBytewise.begin(123);
93 UdpBytewise.beginPacket(address, 123);
94 UdpBytewise.write(B11100011); // LI, Version, Mode
95 UdpBytewise.write(0); // Stratum
96 UdpBytewise.write(6); // Polling Interval
97 UdpBytewise.write(0xEC); // Peer Clock Precision
98 write_n(0, 8); // Root Delay & Root Dispersion
99 UdpBytewise.write(49);
100 UdpBytewise.write(0x4E);
101 UdpBytewise.write(49);
102 UdpBytewise.write(52);
103 write_n(0, 32); //Reference and time stamps
104 UdpBytewise.endPacket();
107 unsigned long getUlong()
109 unsigned long ulong = (unsigned long)UdpBytewise.read() << 24;
110 ulong |= (unsigned long)UdpBytewise.read() << 16;
111 ulong |= (unsigned long)UdpBytewise.read() << 8;
112 ulong |= (unsigned long)UdpBytewise.read();
116 void write_n(int what, int how_many)
118 for( int i = 0; i < how_many; i++ )
119 UdpBytewise.write(what);