Skip to content

Commit b14993d

Browse files
authored
Merge pull request #1687 from arduino/karlsoderby/giga-ntp
[GIGA R1 WiFi] Add NTP timezone example
2 parents 1293b98 + 693dd24 commit b14993d

File tree

1 file changed

+187
-0
lines changed
  • content/hardware/10.mega/boards/giga-r1-wifi/tutorials/giga-wifi

1 file changed

+187
-0
lines changed

content/hardware/10.mega/boards/giga-r1-wifi/tutorials/giga-wifi/giga-wifi.md

Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,193 @@ void printWifiStatus()
346346
}
347347
```
348348

349+
### Wi-Fi RTC Example with Timezone Adjustment
350+
351+
This example provides an option to set the timezone. As the received epoch is based on GMT time, you can input e.g. `-1` or `5` which represents the hours. The `timezone` variable is changed at the top of the example.
352+
353+
```arduino
354+
/*
355+
Udp NTP Client
356+
357+
Get the time from a Network Time Protocol (NTP) time server
358+
Demonstrates use of UDP sendPacket and ReceivePacket
359+
For more on NTP time servers and the messages needed to communicate with them,
360+
see http://en.wikipedia.org/wiki/Network_Time_Protocol
361+
362+
created 4 Sep 2010
363+
by Michael Margolis
364+
modified 9 Apr 2012
365+
by Tom Igoe
366+
modified 28 Dec 2022
367+
by Giampaolo Mancini
368+
369+
This code is in the public domain.
370+
*/
371+
372+
#include <WiFi.h>
373+
#include <WiFiUdp.h>
374+
#include <mbed_mktime.h>
375+
376+
int timezone = -1; //this is GMT -1.
377+
378+
int status = WL_IDLE_STATUS;
379+
380+
char ssid[] = "Flen"; // your network SSID (name)
381+
char pass[] = ""; // your network password (use for WPA, or use as key for WEP)
382+
383+
int keyIndex = 0; // your network key index number (needed only for WEP)
384+
385+
unsigned int localPort = 2390; // local port to listen for UDP packets
386+
387+
// IPAddress timeServer(162, 159, 200, 123); // pool.ntp.org NTP server
388+
389+
constexpr auto timeServer{ "pool.ntp.org" };
390+
391+
const int NTP_PACKET_SIZE = 48; // NTP timestamp is in the first 48 bytes of the message
392+
393+
byte packetBuffer[NTP_PACKET_SIZE]; // buffer to hold incoming and outgoing packets
394+
395+
// A UDP instance to let us send and receive packets over UDP
396+
WiFiUDP Udp;
397+
398+
constexpr unsigned long printInterval{ 1000 };
399+
unsigned long printNow{};
400+
401+
void setup() {
402+
// Open serial communications and wait for port to open:
403+
Serial.begin(9600);
404+
while (!Serial) {
405+
; // wait for serial port to connect. Needed for native USB port only
406+
}
407+
408+
// check for the WiFi module:
409+
if (WiFi.status() == WL_NO_SHIELD) {
410+
Serial.println("Communication with WiFi module failed!");
411+
// don't continue
412+
while (true)
413+
;
414+
}
415+
416+
// attempt to connect to WiFi network:
417+
while (status != WL_CONNECTED) {
418+
Serial.print("Attempting to connect to SSID: ");
419+
Serial.println(ssid);
420+
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
421+
status = WiFi.begin(ssid, pass);
422+
423+
// wait 10 seconds for connection:
424+
delay(10000);
425+
}
426+
427+
Serial.println("Connected to WiFi");
428+
printWifiStatus();
429+
430+
setNtpTime();
431+
}
432+
433+
void loop() {
434+
if (millis() > printNow) {
435+
Serial.print("System Clock: ");
436+
Serial.println(getLocaltime());
437+
printNow = millis() + printInterval;
438+
}
439+
}
440+
441+
void setNtpTime() {
442+
Udp.begin(localPort);
443+
sendNTPpacket(timeServer);
444+
delay(1000);
445+
parseNtpPacket();
446+
}
447+
448+
// send an NTP request to the time server at the given address
449+
unsigned long sendNTPpacket(const char* address) {
450+
memset(packetBuffer, 0, NTP_PACKET_SIZE);
451+
packetBuffer[0] = 0b11100011; // LI, Version, Mode
452+
packetBuffer[1] = 0; // Stratum, or type of clock
453+
packetBuffer[2] = 6; // Polling Interval
454+
packetBuffer[3] = 0xEC; // Peer Clock Precision
455+
// 8 bytes of zero for Root Delay & Root Dispersion
456+
packetBuffer[12] = 49;
457+
packetBuffer[13] = 0x4E;
458+
packetBuffer[14] = 49;
459+
packetBuffer[15] = 52;
460+
461+
Udp.beginPacket(address, 123); // NTP requests are to port 123
462+
Udp.write(packetBuffer, NTP_PACKET_SIZE);
463+
Udp.endPacket();
464+
}
465+
466+
unsigned long parseNtpPacket() {
467+
if (!Udp.parsePacket())
468+
return 0;
469+
470+
Udp.read(packetBuffer, NTP_PACKET_SIZE);
471+
const unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
472+
const unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
473+
const unsigned long secsSince1900 = highWord << 16 | lowWord;
474+
constexpr unsigned long seventyYears = 2208988800UL;
475+
const unsigned long epoch = secsSince1900 - seventyYears;
476+
477+
new_epoch = epoch + (3600 * timezone); //multiply the timezone with 3600 (1 hour)
478+
479+
set_time(new_epoch);
480+
481+
#if defined(VERBOSE)
482+
Serial.print("Seconds since Jan 1 1900 = ");
483+
Serial.println(secsSince1900);
484+
485+
// now convert NTP time into everyday time:
486+
Serial.print("Unix time = ");
487+
// print Unix time:
488+
Serial.println(epoch);
489+
490+
// print the hour, minute and second:
491+
Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT)
492+
Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day)
493+
Serial.print(':');
494+
if (((epoch % 3600) / 60) < 10) {
495+
// In the first 10 minutes of each hour, we'll want a leading '0'
496+
Serial.print('0');
497+
}
498+
Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute)
499+
Serial.print(':');
500+
if ((epoch % 60) < 10) {
501+
// In the first 10 seconds of each minute, we'll want a leading '0'
502+
Serial.print('0');
503+
}
504+
Serial.println(epoch % 60); // print the second
505+
#endif
506+
507+
return epoch;
508+
}
509+
510+
String getLocaltime() {
511+
char buffer[32];
512+
tm t;
513+
_rtc_localtime(time(NULL), &t, RTC_FULL_LEAP_YEAR_SUPPORT);
514+
strftime(buffer, 32, "%Y-%m-%d %k:%M:%S", &t);
515+
return String(buffer);
516+
}
517+
518+
void printWifiStatus() {
519+
// print the SSID of the network you're attached to:
520+
Serial.print("SSID: ");
521+
Serial.println(WiFi.SSID());
522+
523+
// print your board's IP address:
524+
IPAddress ip = WiFi.localIP();
525+
Serial.print("IP Address: ");
526+
Serial.println(ip);
527+
528+
// print the received signal strength:
529+
long rssi = WiFi.RSSI();
530+
Serial.print("signal strength (RSSI):");
531+
Serial.print(rssi);
532+
Serial.println(" dBm");
533+
}
534+
```
535+
349536
### Scan Networks
350537

351538
```arduino

0 commit comments

Comments
 (0)