|
| 1 | + |
| 2 | +/* |
| 3 | + Name: wioTerm_ntp.ino |
| 4 | + Sensors: |
| 5 | + Version: 1.0.0 |
| 6 | + Created: 9/7/2020 04:30:00 PM |
| 7 | + Author: Jim Hamilton |
| 8 | + Company: Sannox Systems Pty Ltd |
| 9 | +
|
| 10 | + Details: Example of setting a rtc via ntp using the Wio Terminal |
| 11 | +
|
| 12 | +******* Updates ******* |
| 13 | +
|
| 14 | +Date: |
| 15 | +
|
| 16 | + 2020-07-09 |
| 17 | + + initial code |
| 18 | +
|
| 19 | +Notes: |
| 20 | + Uses Adafruit RTClib for DateTime functions and rtc control |
| 21 | + https://github.com/adafruit/RTClib |
| 22 | +
|
| 23 | + Uses millisDelay for non blocking timers |
| 24 | + https://www.forward.com.au/pfod/ArduinoProgramming/TimingDelaysInArduino.html |
| 25 | +
|
| 26 | + Example based on the Arduino WifiUdpNtpClient example |
| 27 | +
|
| 28 | + NTP servers can be called via name or ip address, use only servers that can |
| 29 | + repsond to IPv4 requests. |
| 30 | +
|
| 31 | +*/ |
| 32 | + |
| 33 | +// switch between local and remote time servers |
| 34 | +// comment out to use remote server |
| 35 | +#define USELOCALNTP |
| 36 | + |
| 37 | +#include <AtWiFi.h> |
| 38 | +#include <millisDelay.h> |
| 39 | +#include <Wire.h> |
| 40 | +#include <RTClib.h> |
| 41 | + |
| 42 | + |
| 43 | +const char ssid[] = "your-ssid"; // add your required ssid |
| 44 | +const char password[] = "your-passowrd"; // add your own netywork password |
| 45 | + |
| 46 | +millisDelay updateDelay; // the update delay object. used for ntp periodic update. |
| 47 | + |
| 48 | +unsigned int localPort = 2390; // local port to listen for UDP packets |
| 49 | + |
| 50 | +#ifdef USELOCALNTP |
| 51 | + char timeServer[] = "n.n.n.n"; // local NTP server |
| 52 | +#else |
| 53 | + char timeServer[] = "time.nist.gov"; // extenral NTP server e.g. time.nist.gov |
| 54 | +#endif |
| 55 | +const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message |
| 56 | + |
| 57 | +byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets |
| 58 | + |
| 59 | +// declare a time object |
| 60 | +DateTime now; |
| 61 | + |
| 62 | +// define WiFI client |
| 63 | +WiFiClient client; |
| 64 | + |
| 65 | +//The udp library class |
| 66 | +WiFiUDP udp; |
| 67 | + |
| 68 | +// localtime |
| 69 | +unsigned long devicetime; |
| 70 | + |
| 71 | +RTC_DS3231 rtc; |
| 72 | + |
| 73 | +// for use by the Adafuit RTClib library |
| 74 | +char daysOfTheWeek[7][12] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; |
| 75 | + |
| 76 | +void setup() { |
| 77 | + |
| 78 | + Serial.begin(115200); |
| 79 | + |
| 80 | + while (!Serial); // wait for serial port to connect. Needed for native USB |
| 81 | + |
| 82 | + |
| 83 | + // setup network before rtc check |
| 84 | + connectToWiFi(ssid, password); |
| 85 | + |
| 86 | + // get the time via NTP (udp) call to time server |
| 87 | + // getNTPtime returns epoch UTC time adjusted for timezone but not daylight savings |
| 88 | + // time |
| 89 | + devicetime = getNTPtime(); |
| 90 | + |
| 91 | + // check if rtc present |
| 92 | + if (devicetime == 0) { |
| 93 | + Serial.println("Failed to get time from network time server."); |
| 94 | + } |
| 95 | + |
| 96 | + if (!rtc.begin()) { |
| 97 | + Serial.println("Couldn't find RTC"); |
| 98 | + while (1) delay(10); // stop operating |
| 99 | + } |
| 100 | + |
| 101 | + // check if rtc has lost power i.e. battery not present or flat or new device |
| 102 | + if (rtc.lostPower()) { |
| 103 | + |
| 104 | + Serial.println("RTC lost power, let's set the time!"); |
| 105 | + // When time needs to be set on a new device, or after a power loss, |
| 106 | + rtc.adjust(DateTime(devicetime)); |
| 107 | + } |
| 108 | + // get and print the current rtc time |
| 109 | + now = rtc.now(); |
| 110 | + Serial.print("RTC time is: "); |
| 111 | + Serial.println(now.timestamp(DateTime::TIMESTAMP_FULL)); |
| 112 | + |
| 113 | + // adjust time using ntp time |
| 114 | + rtc.adjust(DateTime(devicetime)); |
| 115 | + |
| 116 | + // print boot update details |
| 117 | + Serial.println("RTC (boot) time updated."); |
| 118 | + // get and print the adjusted rtc time |
| 119 | + now = rtc.now(); |
| 120 | + Serial.print("Adjusted RTC (boot) time is: "); |
| 121 | + Serial.println(now.timestamp(DateTime::TIMESTAMP_FULL)); |
| 122 | + |
| 123 | + // start millisdelays timers as required, adjust to suit requirements |
| 124 | + updateDelay.start(12 * 60 * 60 * 1000); // update time via ntp every 12 hrs |
| 125 | + |
| 126 | +} |
| 127 | + |
| 128 | +void loop() { |
| 129 | + |
| 130 | + if (updateDelay.justFinished()) { // 12 hour loop |
| 131 | + // repeat timer |
| 132 | + updateDelay.repeat(); // repeat |
| 133 | + |
| 134 | + // update rtc time |
| 135 | + devicetime = getNTPtime(); |
| 136 | + if (devicetime == 0) { |
| 137 | + Serial.println("Failed to get time from network time server."); |
| 138 | + } |
| 139 | + else { |
| 140 | + rtc.adjust(DateTime(devicetime)); |
| 141 | + Serial.println(""); |
| 142 | + Serial.println("rtc time updated."); |
| 143 | + // get and print the adjusted rtc time |
| 144 | + now = rtc.now(); |
| 145 | + Serial.print("Adjusted RTC time is: "); |
| 146 | + Serial.println(now.timestamp(DateTime::TIMESTAMP_FULL)); |
| 147 | + } |
| 148 | + } |
| 149 | +} |
| 150 | + |
| 151 | + |
| 152 | +void connectToWiFi(const char* ssid, const char* pwd) { |
| 153 | + Serial.println("Connecting to WiFi network: " + String(ssid)); |
| 154 | + |
| 155 | + // delete old config |
| 156 | + WiFi.disconnect(true); |
| 157 | + |
| 158 | + Serial.println("Waiting for WIFI connection..."); |
| 159 | + |
| 160 | + //Initiate connection |
| 161 | + WiFi.begin(ssid, pwd); |
| 162 | + |
| 163 | + while (WiFi.status() != WL_CONNECTED) { |
| 164 | + delay(500); |
| 165 | + } |
| 166 | + |
| 167 | + Serial.println("Connected."); |
| 168 | + printWifiStatus(); |
| 169 | + |
| 170 | +} |
| 171 | + |
| 172 | + |
| 173 | +unsigned long getNTPtime() { |
| 174 | + |
| 175 | + // module returns a unsigned long time valus as secs since Jan 1, 1970 |
| 176 | + // unix time or 0 if a problem encounted |
| 177 | + |
| 178 | + //only send data when connected |
| 179 | + if (WiFi.status() == WL_CONNECTED) { |
| 180 | + //initializes the UDP state |
| 181 | + //This initializes the transfer buffer |
| 182 | + udp.begin(WiFi.localIP(), localPort); |
| 183 | + |
| 184 | + sendNTPpacket(timeServer); // send an NTP packet to a time server |
| 185 | + // wait to see if a reply is available |
| 186 | + delay(1000); |
| 187 | + if (udp.parsePacket()) { |
| 188 | + Serial.println("udp packet received"); |
| 189 | + Serial.println(""); |
| 190 | + // We've received a packet, read the data from it |
| 191 | + udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer |
| 192 | + |
| 193 | + //the timestamp starts at byte 40 of the received packet and is four bytes, |
| 194 | + // or two words, long. First, extract the two words: |
| 195 | + |
| 196 | + unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); |
| 197 | + unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); |
| 198 | + // combine the four bytes (two words) into a long integer |
| 199 | + // this is NTP time (seconds since Jan 1 1900): |
| 200 | + unsigned long secsSince1900 = highWord << 16 | lowWord; |
| 201 | + // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: |
| 202 | + const unsigned long seventyYears = 2208988800UL; |
| 203 | + // subtract seventy years: |
| 204 | + unsigned long epoch = secsSince1900 - seventyYears; |
| 205 | + |
| 206 | + // adjust time for timezone offset in secs +/- from UTC |
| 207 | + // WA time offset from UTC is +8 hours (28,800 secs) |
| 208 | + // + East of GMT |
| 209 | + // - West of GMT |
| 210 | + long tzOffset = 28800UL; |
| 211 | + |
| 212 | + // WA local time |
| 213 | + unsigned long adjustedTime; |
| 214 | + return adjustedTime = epoch + tzOffset; |
| 215 | + } |
| 216 | + else { |
| 217 | + // were not able to parse the udp packet successfully |
| 218 | + // clear down the udp connection |
| 219 | + udp.stop(); |
| 220 | + return 0; // zero indicates a failure |
| 221 | + } |
| 222 | + // not calling ntp time frequently, stop releases resources |
| 223 | + udp.stop(); |
| 224 | + } |
| 225 | + else { |
| 226 | + // network not connected |
| 227 | + return 0; |
| 228 | + } |
| 229 | + |
| 230 | +} |
| 231 | + |
| 232 | +// send an NTP request to the time server at the given address |
| 233 | +unsigned long sendNTPpacket(const char* address) { |
| 234 | + // set all bytes in the buffer to 0 |
| 235 | + for (int i = 0; i < NTP_PACKET_SIZE; ++i) { |
| 236 | + packetBuffer[i] = 0; |
| 237 | + } |
| 238 | + // Initialize values needed to form NTP request |
| 239 | + // (see URL above for details on the packets) |
| 240 | + packetBuffer[0] = 0b11100011; // LI, Version, Mode |
| 241 | + packetBuffer[1] = 0; // Stratum, or type of clock |
| 242 | + packetBuffer[2] = 6; // Polling Interval |
| 243 | + packetBuffer[3] = 0xEC; // Peer Clock Precision |
| 244 | + // 8 bytes of zero for Root Delay & Root Dispersion |
| 245 | + packetBuffer[12] = 49; |
| 246 | + packetBuffer[13] = 0x4E; |
| 247 | + packetBuffer[14] = 49; |
| 248 | + packetBuffer[15] = 52; |
| 249 | + |
| 250 | + // all NTP fields have been given values, now |
| 251 | + // you can send a packet requesting a timestamp: |
| 252 | + udp.beginPacket(address, 123); //NTP requests are to port 123 |
| 253 | + udp.write(packetBuffer, NTP_PACKET_SIZE); |
| 254 | + udp.endPacket(); |
| 255 | +} |
| 256 | + |
| 257 | +void printWifiStatus() { |
| 258 | + // print the SSID of the network you're attached to: |
| 259 | + Serial.println(""); |
| 260 | + Serial.print("SSID: "); |
| 261 | + Serial.println(WiFi.SSID()); |
| 262 | + |
| 263 | + // print your WiFi shield's IP address: |
| 264 | + IPAddress ip = WiFi.localIP(); |
| 265 | + Serial.print("IP Address: "); |
| 266 | + Serial.println(ip); |
| 267 | + |
| 268 | + // print the received signal strength: |
| 269 | + long rssi = WiFi.RSSI(); |
| 270 | + Serial.print("signal strength (RSSI):"); |
| 271 | + Serial.print(rssi); |
| 272 | + Serial.println(" dBm"); |
| 273 | + Serial.println(""); |
| 274 | +} |
0 commit comments