1
1
#include < WiFi.h>
2
2
#include " time.h"
3
+ #include " sntp.h"
3
4
4
5
const char * ssid = " YOUR_SSID" ;
5
6
const char * password = " YOUR_PASS" ;
6
7
7
- const char * ntpServer = " pool.ntp.org" ;
8
+ const char * ntpServer1 = " pool.ntp.org" ;
9
+ const char * ntpServer2 = " time.nist.gov" ;
8
10
const long gmtOffset_sec = 3600 ;
9
11
const int daylightOffset_sec = 3600 ;
10
12
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
+
11
15
void printLocalTime ()
12
16
{
13
17
struct tm timeinfo;
14
18
if (!getLocalTime (&timeinfo)){
15
- Serial.println (" Failed to obtain time " );
19
+ Serial.println (" No time available (yet) " );
16
20
return ;
17
21
}
18
22
Serial.println (&timeinfo, " %A, %B %d %Y %H:%M:%S" );
19
23
}
20
24
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
+
21
32
void setup ()
22
33
{
23
34
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
+
25
63
// connect to WiFi
26
64
Serial.printf (" Connecting to %s " , ssid);
27
65
WiFi.begin (ssid, password);
@@ -30,18 +68,11 @@ void setup()
30
68
Serial.print (" ." );
31
69
}
32
70
Serial.println (" CONNECTED" );
33
-
34
- // init and get the time
35
- configTime (gmtOffset_sec, daylightOffset_sec, ntpServer);
36
- printLocalTime ();
37
71
38
- // disconnect WiFi as it's no longer needed
39
- WiFi.disconnect (true );
40
- WiFi.mode (WIFI_OFF);
41
72
}
42
73
43
74
void loop ()
44
75
{
45
- delay (1000 );
46
- printLocalTime ();
76
+ delay (5000 );
77
+ printLocalTime (); // it will take some time to sync time :)
47
78
}
0 commit comments