This repository has been archived by the owner on Jan 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RTC_Ethernet.ino
530 lines (410 loc) · 16.2 KB
/
RTC_Ethernet.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
/****************************************************************************************************************************
RTC_Ethernet.ino
For all Generic boards such as ESP8266, ESP32, SAMD21/SAMD51, nRF52, STM32F/L/H/G/WB/MP1
with WiFiNINA, ESP8266/ESP32 WiFi, ESP8266-AT, W5x00, ENC28J60, LAN8742A Ethernet modules/shields
DS323x_Generic Arduino library for DS3231/DS3232 Extremely Accurate I2C-Integrated RTC/TCXO/Crystal.
Based on and modified from Hideaki Tai's DS323x Library (https://github.com/hideakitai/DS323x)
Built by Khoi Hoang https://github.com/khoih-prog/DS323x_Generic
Licensed under MIT license
*****************************************************************************************************************************/
// Important Note: You have to modify and run example WriteRules in order to read from correct TZ file
#include "defines.h"
//////////////////////////////////////////
// To be included only in main(), .ino with setup() to avoid `Multiple Definitions` Linker Error
#include <Timezone_Generic.h> // https://github.com/khoih-prog/Timezone_Generic
#include <DS323x_Generic.h> // https://github.com/khoih-prog/DS323x_Generic
DS323x rtc;
//////////////////////////////////////////
#define USING_INITIALIZED_TZ false //true
#if USING_INITIALIZED_TZ
// US Eastern Time Zone (New York, Detroit,Toronto)
TimeChangeRule myDST = {"EDT", Second, Sun, Mar, 2, -240}; // Daylight time = UTC - 4 hours
TimeChangeRule mySTD = {"EST", First, Sun, Nov, 2, -300}; // Standard time = UTC - 5 hours
//Timezone myTZ(myDST, mySTD);
Timezone *myTZ;
#else
// Allow a "blank" TZ object then use begin() method to set the actual TZ.
// Feature added by 6v6gt (https://forum.arduino.cc/index.php?topic=711259)
//Timezone myTZ ;
Timezone *myTZ;
TimeChangeRule myDST;
TimeChangeRule mySTD;
#endif
TimeChangeRule *tcr; //pointer to the time change rule, use to get TZ abbrev
//////////////////////////////////////////
char timeServer[] = "time.nist.gov"; // NTP server
unsigned int localPort = 2390; // local port to listen for UDP packets
const int NTP_PACKET_SIZE = 48; // NTP timestamp is in the first 48 bytes of the message
const int UDP_TIMEOUT = 2000; // timeout in miliseconds to wait for an UDP packet to arrive
byte packetBuffer[NTP_PACKET_SIZE]; // buffer to hold incoming and outgoing packets
// A UDP instance to let us send and receive packets over UDP
EthernetUDP Udp;
// send an NTP request to the time server at the given address
void sendNTPpacket(char *ntpSrv)
{
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
packetBuffer[0] = 0b11100011; // LI, Version, Mode
packetBuffer[1] = 0; // Stratum, or type of clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
Udp.beginPacket(ntpSrv, 123); //NTP requests are to port 123
Udp.write(packetBuffer, NTP_PACKET_SIZE);
Udp.endPacket();
}
void getNTPTime()
{
static bool gotCurrentTime = false;
// Just get the correct time once
if (!gotCurrentTime)
{
sendNTPpacket(timeServer); // send an NTP packet to a time server
// wait for a reply for UDP_TIMEOUT miliseconds
static unsigned long startMs = millis();
while (!Udp.available() && (millis() - startMs) < UDP_TIMEOUT) {}
if (Udp.parsePacket())
{
Serial.println(F("Packet received"));
// We've received a packet, read the data from it
Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
//the timestamp starts at byte 40 of the received packet and is four bytes,
// or two words, long. First, esxtract the two words:
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;
Serial.print(F("Seconds since Jan 1 1900 = "));
Serial.println(secsSince1900);
// now convert NTP time into everyday time:
Serial.print(F("Unix time = "));
// Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
const unsigned long seventyYears = 2208988800UL;
// subtract seventy years:
unsigned long epoch = secsSince1900 - seventyYears;
// print Unix time:
Serial.println(epoch);
// Get the time_t from epoch
time_t epoch_t = epoch;
// set the system time to UTC
// warning: assumes that compileTime() returns US EDT
// adjust the following line accordingly if you're in another time zone
setTime(epoch_t);
// Update RTC
// Can use either one of these functions
// 1) DateTime(tmElements_t). Must create tmElements_t if not present
//tmElements_t tm;
//breakTime(epoch_t, tm);
//rtc.now( DateTime(tm) );
// 2) DateTime(year, month, day, hour, min, sec)
//rtc.now( DateTime(year(epoch_t), month(epoch_t), day(epoch_t), hour(epoch_t), minute(epoch_t), second(epoch_t) ) );
// 3) DateTime (time_t)
//rtc.now( DateTime(epoch_t) );
// 4) DateTime(unsigned long epoch). The best and easiest way
rtc.now( DateTime((uint32_t) epoch) );
// print the hour, minute and second:
Serial.print(F("The UTC time is ")); // UTC is the time at Greenwich Meridian (GMT)
Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day)
Serial.print(':');
if (((epoch % 3600) / 60) < 10)
{
// In the first 10 minutes of each hour, we'll want a leading '0'
Serial.print('0');
}
Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute)
Serial.print(':');
if ((epoch % 60) < 10)
{
// In the first 10 seconds of each minute, we'll want a leading '0'
Serial.print('0');
}
Serial.println(epoch % 60); // print the second
gotCurrentTime = true;
}
else
{
// wait ten seconds before asking for the time again
//delay(10000);
}
}
}
//////////////////////////////////////////
// format and print a time_t value, with a time zone appended.
void printDateTime(time_t t, const char *tz)
{
char buf[32];
char m[4]; // temporary storage for month string (DateStrings.cpp uses shared buffer)
strcpy(m, monthShortStr(month(t)));
sprintf(buf, "%.2d:%.2d:%.2d %s %.2d %s %d %s",
hour(t), minute(t), second(t), dayShortStr(weekday(t)), day(t), m, year(t), tz);
Serial.println(buf);
}
void setup()
{
Serial.begin(115200);
while (!Serial);
delay(200);
Serial.print(F("\nStart RTC_Ethernet on "));
Serial.print(BOARD_NAME);
Serial.print(F(" with "));
Serial.println(SHIELD_TYPE);
Serial.println(TIMEZONE_GENERIC_VERSION);
Serial.println(DS323X_GENERIC_VERSION);
#if defined(TIMEZONE_GENERIC_VERSION_MIN)
if (TIMEZONE_GENERIC_VERSION_INT < TIMEZONE_GENERIC_VERSION_MIN)
{
Serial.print("Warning. Must use this example on Version equal or later than : ");
Serial.println(TIMEZONE_GENERIC_VERSION_MIN_TARGET);
}
#endif
#if defined(PIN_WIRE_SDA)
// Arduino core, ESP8266, Adafruit, Teensy
TZ_LOGWARN(F("Default DS323X pinout:"));
TZ_LOGWARN1(F("SDA:"), PIN_WIRE_SDA);
TZ_LOGWARN1(F("SCL:"), PIN_WIRE_SCL);
#elif defined(PIN_WIRE0_SDA)
// arduino-pico core
TZ_LOGWARN(F("Default DS323X pinout:"));
TZ_LOGWARN1(F("SDA:"), PIN_WIRE0_SDA);
TZ_LOGWARN1(F("SCL:"), PIN_WIRE0_SCL);
#elif defined(ESP32)
// ESP32
TZ_LOGWARN(F("Default DS323X pinout:"));
TZ_LOGWARN1(F("SDA:"), SDA);
TZ_LOGWARN1(F("SCL:"), SCL);
#endif
Wire.begin();
#if USE_ETHERNET_PORTENTA_H7
TZ_LOGWARN(F("======== USE_PORTENTA_H7_ETHERNET ========"));
#elif USE_NATIVE_ETHERNET
TZ_LOGWARN(F("======== USE_NATIVE_ETHERNET ========"));
#elif USE_QN_ETHERNET
TZ_LOGWARN(F("======== USE_QN_ETHERNET ========"));
#elif USE_ETHERNET_GENERIC
TZ_LOGWARN(F("=========== USE_ETHERNET_GENERIC ==========="));
#elif USE_ETHERNET_ESP8266
TZ_LOGWARN(F("=========== USE_ETHERNET_ESP8266 ==========="));
#elif USE_ETHERNET_ENC
TZ_LOGWARN(F("=========== USE_ETHERNET_ENC ==========="));
#else
TZ_LOGWARN(F("========================="));
#endif
#if !(USE_NATIVE_ETHERNET || USE_QN_ETHERNET || USE_ETHERNET_PORTENTA_H7)
TZ_LOGWARN(F("Default SPI pinout:"));
TZ_LOGWARN1(F("MOSI:"), MOSI);
TZ_LOGWARN1(F("MISO:"), MISO);
TZ_LOGWARN1(F("SCK:"), SCK);
TZ_LOGWARN1(F("SS:"), SS);
TZ_LOGWARN(F("========================="));
#if defined(ESP8266)
// For ESP8266, change for other boards if necessary
#ifndef USE_THIS_SS_PIN
#define USE_THIS_SS_PIN D2 // For ESP8266
#endif
TZ_LOGWARN1(F("ESP8266 setCsPin:"), USE_THIS_SS_PIN);
#if ( USE_ETHERNET_GENERIC || USE_ETHERNET_ENC )
// For ESP8266
// Pin D0(GPIO16) D1(GPIO5) D2(GPIO4) D3(GPIO0) D4(GPIO2) D8
// EthernetGeneric X X X X X 0
// Ethernet_ESP8266 0 0 0 0 0 0
// D2 is safe to used for Ethernet, Ethernet2, Ethernet3, EthernetLarge libs
// Must use library patch for Ethernet, EthernetLarge libraries
Ethernet.init (USE_THIS_SS_PIN);
#elif USE_CUSTOM_ETHERNET
// You have to add initialization for your Custom Ethernet here
// This is just an example to setCSPin to USE_THIS_SS_PIN, and can be not correct and enough
Ethernet.init(USE_THIS_SS_PIN);
#endif //( USE_ETHERNET_GENERIC || USE_ETHERNET_ENC )
#elif defined(ESP32)
// You can use Ethernet.init(pin) to configure the CS pin
//Ethernet.init(10); // Most Arduino shields
//Ethernet.init(5); // MKR ETH shield
//Ethernet.init(0); // Teensy 2.0
//Ethernet.init(20); // Teensy++ 2.0
//Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet
//Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet
#ifndef USE_THIS_SS_PIN
#define USE_THIS_SS_PIN 5 //22 // For ESP32
#endif
TZ_LOGWARN1(F("ESP32 setCsPin:"), USE_THIS_SS_PIN);
// For other boards, to change if necessary
#if ( USE_ETHERNET_GENERIC || USE_ETHERNET_ENC )
// Must use library patch for Ethernet, EthernetLarge libraries
// ESP32 => GPIO2,4,5,13,15,21,22 OK with Ethernet, Ethernet2, EthernetLarge
// ESP32 => GPIO2,4,5,15,21,22 OK with Ethernet3
//Ethernet.setCsPin (USE_THIS_SS_PIN);
Ethernet.init (USE_THIS_SS_PIN);
#elif USE_CUSTOM_ETHERNET
// You have to add initialization for your Custom Ethernet here
// This is just an example to setCSPin to USE_THIS_SS_PIN, and can be not correct and enough
Ethernet.init(USE_THIS_SS_PIN);
#endif //( USE_ETHERNET_GENERIC || USE_ETHERNET_ENC )
#elif ETHERNET_USE_RPIPICO
pinMode(USE_THIS_SS_PIN, OUTPUT);
digitalWrite(USE_THIS_SS_PIN, HIGH);
// ETHERNET_USE_RPIPICO, use default SS = 5 or 17
#ifndef USE_THIS_SS_PIN
#if defined(ARDUINO_ARCH_MBED)
#define USE_THIS_SS_PIN 17 // For Arduino Mbed core
#else
#define USE_THIS_SS_PIN 17 // For E.Philhower core
#endif
#endif
TZ_LOGWARN1(F("RPIPICO setCsPin:"), USE_THIS_SS_PIN);
// For other boards, to change if necessary
#if ( USE_ETHERNET_GENERIC || USE_ETHERNET_ENC )
// Must use library patch for Ethernet, EthernetLarge libraries
// For RPI Pico using Arduino Mbed RP2040 core
// SCK: GPIO2, MOSI: GPIO3, MISO: GPIO4, SS/CS: GPIO5
// For RPI Pico using E. Philhower RP2040 core
// SCK: GPIO18, MOSI: GPIO19, MISO: GPIO16, SS/CS: GPIO17
// Default pin 5/17 to SS/CS
//Ethernet.setCsPin (USE_THIS_SS_PIN);
Ethernet.init (USE_THIS_SS_PIN);
#endif //( USE_ETHERNET_GENERIC || USE_ETHERNET_ENC )
#else //defined(ESP8266)
// unknown board, do nothing, use default SS = 10
#ifndef USE_THIS_SS_PIN
#define USE_THIS_SS_PIN 10 // For other boards
#endif
#if defined(BOARD_NAME)
TZ_LOGWARN3(F("Board :"), BOARD_NAME, F(", setCsPin:"), USE_THIS_SS_PIN);
#else
TZ_LOGWARN1(F("Unknown board setCsPin:"), USE_THIS_SS_PIN);
#endif
// For other boards, to change if necessary
#if ( USE_ETHERNET_GENERIC || USE_ETHERNET_ENC )
// Must use library patch for Ethernet, Ethernet2, EthernetLarge libraries
Ethernet.init (USE_THIS_SS_PIN);
#elif USE_CUSTOM_ETHERNET
// You have to add initialization for your Custom Ethernet here
// This is just an example to setCSPin to USE_THIS_SS_PIN, and can be not correct and enough
Ethernet.init(USE_THIS_SS_PIN);
#endif //( USE_ETHERNET_GENERIC || USE_ETHERNET_ENC )
#endif // defined(ESP8266)
#endif // #if !(USE_NATIVE_ETHERNET || USE_QN_ETHERNET || USE_ETHERNET_PORTENTA_H7)
#if !(USE_NATIVE_ETHERNET || USE_QN_ETHERNET || USE_ETHERNET_PORTENTA_H7)
// Just info to know how to connect correctly
Serial.println(F("========================="));
Serial.println(F("Currently Used SPI pinout:"));
Serial.print(F("MOSI:"));
Serial.println(MOSI);
Serial.print(F("MISO:"));
Serial.println(MISO);
Serial.print(F("SCK:"));
Serial.println(SCK);
Serial.print(F("SS:"));
Serial.println(SS);
Serial.println(F("========================="));
#endif
#if (USE_QN_ETHERNET)
#define USING_DHCP false //true
#if USING_DHCP
// Start the Ethernet connection, using DHCP
Serial.print("Initialize QNEthernet using DHCP => ");
Ethernet.begin();
#else
// Start the Ethernet connection, using static IP
Serial.print("Initialize QNEthernet using static IP => ");
Ethernet.begin(myIP, myNetmask, myGW);
Ethernet.setDNSServerIP(mydnsServer);
#endif
if (!Ethernet.waitForLocalIP(5000))
{
Serial.println(F("Failed to configure Ethernet"));
if (!Ethernet.linkStatus())
{
Serial.println(F("Ethernet cable is not connected."));
}
// Stay here forever
while (true)
{
delay(1);
}
}
if (!Ethernet.waitForLink(5000))
{
Serial.println(F("Failed to wait for Link"));
}
#else
// start the ethernet connection and the server:
// Use DHCP dynamic IP and random mac
uint16_t index = millis() % NUMBER_OF_MAC;
// Use Static IP
//Ethernet.begin(mac[index], myIP);
Ethernet.begin(mac[index]);
Serial.print(F("Using mac index = "));
Serial.println(index);
#endif
// you're connected now, so print out the data
Serial.print(F("You're connected to the network, IP = "));
Serial.println(Ethernet.localIP());
#if (USING_INITIALIZED_TZ)
myTZ = new Timezone(myDST, mySTD);
#else
// Can read this info from EEPROM, storage, etc
String tzName = "EDT/EST" ;
// Time zone rules can be set as below or dynamically built, say through a configuration
// interface, or fetched from eeprom, flash etc.
if ( tzName == "EDT/EST" )
{
// America Eastern Time
myDST = (TimeChangeRule)
{"EDT", Second, Sun, Mar, 2, -240
}; // Daylight time = UTC - 4 hours
mySTD = (TimeChangeRule)
{"EST", First, Sun, Nov, 2, -300
}; // Standard time = UTC - 5 hours
}
else if ( tzName == "CET/CEST" )
{
// central Europe
myDST = (TimeChangeRule)
{"CEST", Last, Sun, Mar, 2, 120
};
mySTD = (TimeChangeRule)
{"CET", Last, Sun, Oct, 3, 60
};
}
else if ( tzName == "GMT/BST" )
{
// UK
myDST = (TimeChangeRule)
{"BST", Last, Sun, Mar, 1, 60
};
mySTD = (TimeChangeRule)
{"GMT", Last, Sun, Oct, 2, 0
};
}
myTZ = new Timezone();
myTZ->init( myDST, mySTD ) ;
#endif
// Comment out for first time run to write TZ rule to filesystem
myTZ->writeRules(0); // write rules to address/offset 0
Serial.println(F("WriteRules done"));
Udp.begin(localPort);
rtc.attach(Wire);
}
void loop()
{
// Get time from NTP once, then update RTC
// You certainly can make NTP check every hour/day to update RTC ti have better accuracy
getNTPTime();
// Display time from RTC
DateTime now = rtc.now();
Serial.println("============================");
time_t utc = now.get_time_t();
time_t local = myTZ->toLocal(utc, &tcr);
printDateTime(utc, "UTC");
printDateTime(local, tcr -> abbrev);
delay(10000);
}