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
/
Copy pathRTL8720_RTC_Time_WiFi.ino
260 lines (196 loc) · 7.9 KB
/
RTL8720_RTC_Time_WiFi.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
/****************************************************************************************************************************
RTL8720_RTC_Time_WiFi.ino
For RTL8720-based boards using internal RTC with RTL8720DN WiFi
Built by Khoi Hoang https://github.com/khoih-prog/RTL8720_RTC
Licensed under MIT license
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 10/08/2021 Initial release to support RTL8720-based boards using internal RTC with RTL8720DN WiFi
*****************************************************************************************************************************/
// Important notes: Currently, RTL8720DN-based boards RTC has no battery backup. So the time will be lost when power down
// Therefore, NTP client is necessary to get NTP time and update RTC.
#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
//////////////////////////////////////////
// US Eastern Time Zone (New York, Detroit)
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;
TimeChangeRule *tcr; //pointer to the time change rule, use to get TZ abbrev
//////////////////////////////////////////
int status = WL_IDLE_STATUS; // the Wifi radio's status
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
WiFiUDP Udp;
time_t currTime;
char datetime_buf[256];
RTL8720_RTC myRTC;
// 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 ime once
if (!gotCurrentTime)
{
sendNTPpacket(timeServer); // send an NTP packet to a time server
// wait to see if a reply is available
delay(1000);
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
myRTC.write(epoch_t);
// 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 RTL8720_RTC_Time_WiFi on ")); Serial.println(BOARD_NAME);
Serial.println(RTL8720_RTC_VERSION);
Serial.println(TIMEZONE_GENERIC_VERSION);
if (WiFi.status() == WL_NO_SHIELD)
{
Serial.println(F("WiFi shield not present"));
// don't continue
while (true);
}
String fv = WiFi.firmwareVersion();
Serial.print("Current Firmware Version = "); Serial.println(fv);
if (fv != LATEST_RTL8720_FIRMWARE)
{
Serial.println("Please upgrade the firmware");
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED)
{
Serial.print("Attempting to connect to SSID: "); Serial.println(ssid);
// Connect to WPA/WPA2 network. 2.4G and 5G are all OK
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.print(F("TZ_NTP_Clock_RTL8720DN started @ IP address: "));
Serial.println(WiFi.localIP());
myTZ = new Timezone(myDST, mySTD);
// Start the RTC
myRTC.init();
Udp.begin(localPort);
}
void displayTime()
{
currTime = myRTC.read();
// Display time from RTC
DateTime now = DateTime(currTime);
time_t utc = now.get_time_t();
time_t local = myTZ->toLocal(utc, &tcr);
printDateTime(utc, "UTC");
printDateTime(local, tcr -> abbrev);
}
void displayRTCTime()
{
static unsigned long displayRTCTime_timeout = 0;
#define DISPLAY_RTC_INTERVAL 60000L
// Send status report every STATUS_REPORT_INTERVAL (60) seconds: we don't need to display frequently.
if ((millis() > displayRTCTime_timeout) || (displayRTCTime_timeout == 0))
{
Serial.println("============================");
displayTime();
displayRTCTime_timeout = millis() + DISPLAY_RTC_INTERVAL;
}
}
void loop()
{
// Get time from NTP once, then update RTC
// You certainly can make NTP check every hour/day to update RTC to have better accuracy
getNTPTime();
displayRTCTime();
}