123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135 |
-
- #include <TimeLib.h>
- #include <Ethernet.h>
- #include <EthernetUdp.h>
- #include <SPI.h>
- byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
- IPAddress timeServer(132, 163, 4, 101);
- const int timeZone = 1;
- EthernetUDP Udp;
- unsigned int localPort = 8888;
- void setup()
- {
- Serial.begin(9600);
- while (!Serial) ;
- delay(250);
- Serial.println("TimeNTP Example");
- if (Ethernet.begin(mac) == 0) {
-
- while (1) {
- Serial.println("Failed to configure Ethernet using DHCP");
- delay(10000);
- }
- }
- Serial.print("IP number assigned by DHCP is ");
- Serial.println(Ethernet.localIP());
- Udp.begin(localPort);
- Serial.println("waiting for sync");
- setSyncProvider(getNtpTime);
- }
- time_t prevDisplay = 0;
- void loop()
- {
- if (timeStatus() != timeNotSet) {
- if (now() != prevDisplay) {
- prevDisplay = now();
- digitalClockDisplay();
- }
- }
- }
- void digitalClockDisplay(){
-
- Serial.print(hour());
- printDigits(minute());
- printDigits(second());
- Serial.print(" ");
- Serial.print(day());
- Serial.print(" ");
- Serial.print(month());
- Serial.print(" ");
- Serial.print(year());
- Serial.println();
- }
- void printDigits(int digits){
-
- Serial.print(":");
- if(digits < 10)
- Serial.print('0');
- Serial.print(digits);
- }
- const int NTP_PACKET_SIZE = 48;
- byte packetBuffer[NTP_PACKET_SIZE];
- time_t getNtpTime()
- {
- while (Udp.parsePacket() > 0) ;
- Serial.println("Transmit NTP Request");
- sendNTPpacket(timeServer);
- uint32_t beginWait = millis();
- while (millis() - beginWait < 1500) {
- int size = Udp.parsePacket();
- if (size >= NTP_PACKET_SIZE) {
- Serial.println("Receive NTP Response");
- Udp.read(packetBuffer, NTP_PACKET_SIZE);
- unsigned long secsSince1900;
-
- secsSince1900 = (unsigned long)packetBuffer[40] << 24;
- secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
- secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
- secsSince1900 |= (unsigned long)packetBuffer[43];
- return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
- }
- }
- Serial.println("No NTP Response :-(");
- return 0;
- }
- void sendNTPpacket(IPAddress &address)
- {
-
- memset(packetBuffer, 0, NTP_PACKET_SIZE);
-
-
- packetBuffer[0] = 0b11100011;
- packetBuffer[1] = 0;
- packetBuffer[2] = 6;
- packetBuffer[3] = 0xEC;
-
- packetBuffer[12] = 49;
- packetBuffer[13] = 0x4E;
- packetBuffer[14] = 49;
- packetBuffer[15] = 52;
-
-
- Udp.beginPacket(address, 123);
- Udp.write(packetBuffer, NTP_PACKET_SIZE);
- Udp.endPacket();
- }
|