11#include < WiFi.h>
22#include " time.h"
3+ #include " sntp.h"
34
45const char * ssid = " YOUR_SSID" ;
56const char * password = " YOUR_PASS" ;
67
7- const char * ntpServer = " pool.ntp.org" ;
8+ const char * ntpServer1 = " pool.ntp.org" ;
9+ const char * ntpServer2 = " time.nist.gov" ;
810const long gmtOffset_sec = 3600 ;
911const int daylightOffset_sec = 3600 ;
1012
13+ const char * time_zone = " CET-1CEST,M3.5.0,M10.5.0/3" ; // TimeZone rule for Europe/Rome including daylight adjustment rules (optional)
14+
1115void printLocalTime ()
1216{
1317 struct tm timeinfo;
1418 if (!getLocalTime (&timeinfo)){
15- Serial.println (" Failed to obtain time " );
19+ Serial.println (" No time available (yet) " );
1620 return ;
1721 }
1822 Serial.println (&timeinfo, " %A, %B %d %Y %H:%M:%S" );
1923}
2024
25+ // Callback function (get's called when time adjusts via NTP)
26+ void timeavailable (struct timeval *t)
27+ {
28+ Serial.println (" Got time adjustment from NTP!" );
29+ printLocalTime ();
30+ }
31+
2132void setup ()
2233{
2334 Serial.begin (115200 );
24-
35+
36+ // set notification call-back function
37+ sntp_set_time_sync_notification_cb ( timeavailable );
38+
39+ /* *
40+ * NTP server address could be aquired via DHCP,
41+ *
42+ * NOTE: This call should be made BEFORE esp32 aquires IP address via DHCP,
43+ * otherwise SNTP option 42 would be rejected by default.
44+ * NOTE: configTime() function call if made AFTER DHCP-client run
45+ * will OVERRIDE aquired NTP server address
46+ */
47+ sntp_servermode_dhcp (1 ); // (optional)
48+
49+ /* *
50+ * This will set configured ntp servers and constant TimeZone/daylightOffset
51+ * should be OK if your time zone does not need to adjust daylightOffset twice a year,
52+ * in such a case time adjustment won't be handled automagicaly.
53+ */
54+ configTime (gmtOffset_sec, daylightOffset_sec, ntpServer1, ntpServer2);
55+
56+ /* *
57+ * A more convenient approach to handle TimeZones with daylightOffset
58+ * would be to specify a environmnet variable with TimeZone definition including daylight adjustmnet rules.
59+ * A list of rules for your zone could be obtained from https://github.com/esp8266/Arduino/blob/master/cores/esp8266/TZ.h
60+ */
61+ // configTzTime(time_zone, ntpServer1, ntpServer2);
62+
2563 // connect to WiFi
2664 Serial.printf (" Connecting to %s " , ssid);
2765 WiFi.begin (ssid, password);
@@ -30,18 +68,11 @@ void setup()
3068 Serial.print (" ." );
3169 }
3270 Serial.println (" CONNECTED" );
33-
34- // init and get the time
35- configTime (gmtOffset_sec, daylightOffset_sec, ntpServer);
36- printLocalTime ();
3771
38- // disconnect WiFi as it's no longer needed
39- WiFi.disconnect (true );
40- WiFi.mode (WIFI_OFF);
4172}
4273
4374void loop ()
4475{
45- delay (1000 );
46- printLocalTime ();
76+ delay (5000 );
77+ printLocalTime (); // it will take some time to sync time :)
4778}
0 commit comments