123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168 |
-
- #include <TimeLib.h>
- #include <EtherCard.h>
- byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
- const char timeServer[] PROGMEM = "pool.ntp.org";
- const int utcOffset = 1;
- #define BUFFER_SIZE 550
- byte Ethernet::buffer[BUFFER_SIZE];
- const unsigned int remotePort = 123;
- void setup()
- {
- Serial.begin(9600);
-
- while (!Serial)
- ;
- delay(250);
-
- Serial.println("TimeNTP_ENC28J60 Example");
-
- if (ether.begin(BUFFER_SIZE, mac) == 0) {
-
- while (1) {
- Serial.println("Failed to access Ethernet controller");
- delay(10000);
- }
- }
-
- if (!ether.dhcpSetup()) {
-
- while (1) {
- Serial.println("Failed to configure Ethernet using DHCP");
- delay(10000);
- }
- }
- ether.printIp("IP number assigned by DHCP is ", ether.myip);
- Serial.println("waiting for sync");
-
- setSyncProvider(getDstCorrectedTime);
- }
- 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);
- }
- time_t getNtpTime()
- {
-
- Serial.println("Transmit NTP Request");
- if (!ether.dnsLookup(timeServer)) {
- Serial.println("DNS failed");
- return 0;
- } else {
-
- ether.ntpRequest(ether.hisip, remotePort);
-
-
- uint32_t beginWait = millis();
- while (millis() - beginWait < 1500) {
- word len = ether.packetReceive();
- ether.packetLoop(len);
- unsigned long secsSince1900 = 0L;
- if (len > 0 && ether.ntpProcessAnswer(&secsSince1900, remotePort)) {
- Serial.println("Receive NTP Response");
- return secsSince1900 - 2208988800UL;
- }
- }
-
- Serial.println("No NTP Response :-(");
- return 0;
- }
- }
- time_t getDstCorrectedTime (void) {
- time_t t = getNtpTime ();
- if (t > 0) {
- TimeElements tm;
- breakTime (t, tm);
- t += (utcOffset + dstOffset (tm.Day, tm.Month, tm.Year + 1970, tm.Hour)) * SECS_PER_HOUR;
- }
- return t;
- }
- byte dstOffset (byte d, byte m, unsigned int y, byte h) {
-
- byte dstOn = (31 - (5 * y / 4 + 4) % 7);
-
- byte dstOff = (31 - (5 * y / 4 + 1) % 7);
- if ((m > 3 && m < 10) ||
- (m == 3 && (d > dstOn || (d == dstOn && h >= 1))) ||
- (m == 10 && (d < dstOff || (d == dstOff && h <= 1))))
- return 1;
- else
- return 0;
- }
|