1
+ // change next line to use with another board/shield
2
+ #include < WiFi.h>
3
+ // #include <ESP8266WiFi.h>
4
+ // #include <WiFi.h>
5
+ // #include <WiFi101.h>
6
+ #include < WiFiUdp.h>
7
+ #include " NTPClient.h"
8
+
9
+ WiFiUDP ntpUDP;
10
+ NTPClient my_time_client (ntpUDP);
11
+
12
+ void connect_wifi (char * ssid,char * password){
13
+ Serial.print (" wifi connecting..." );
14
+ WiFi.begin (ssid,password);
15
+ while (WiFi.status ()!= WL_CONNECTED){
16
+ delay (1000 );
17
+ Serial.print (" ." );
18
+ }
19
+
20
+ Serial.println (" \n wifi connected!" );
21
+ Serial.print (" ip: " );
22
+ Serial.println (WiFi.localIP ());
23
+ Serial.print (" netmask: " );
24
+ Serial.println (WiFi.subnetMask ());
25
+ Serial.print (" gateway: " );
26
+ Serial.println (WiFi.gatewayIP ());
27
+ Serial.print (" channel: " );
28
+ Serial.println (WiFi.channel ());
29
+ Serial.print (" auto-reconnect: " );
30
+ Serial.println (WiFi.getAutoReconnect ());
31
+ }
32
+
33
+ inline void sync_time (){
34
+ my_time_client.begin ();
35
+ my_time_client.setTimeOffset (28800 );
36
+ my_time_client.setUpdateInterval (20000 );
37
+ // my_time_client.setPoolServerName("0.ubuntu.pool.ntp.org");
38
+ my_time_client.setPoolServerName (" 192.168.1.200" );
39
+ // smaller timeout will give you more accuracy
40
+ // but also larger possibility to fail
41
+ my_time_client.setTimeout (800 );
42
+ Serial.println (" syncing..." );
43
+
44
+ while (my_time_client.update ()!=1 ){
45
+ delay (2000 );
46
+ my_time_client.forceUpdate ();
47
+ }
48
+
49
+ Serial.print (" success: " );
50
+ Serial.println (my_time_client.getFormattedTime ());
51
+ }
52
+
53
+ void setup (){
54
+ Serial.begin (230400 );
55
+ Serial.println (" serial inited" );
56
+
57
+ connect_wifi ((char *)" ssid" ,(char *)" pwd" );
58
+ sync_time ();
59
+
60
+ Serial.println (" ready!" );
61
+ }
62
+
63
+ String s_last_time=" s_last_time" ;
64
+
65
+ void loop (){
66
+ String s_time=my_time_client.getFormattedTime ();
67
+ if (s_time!=s_last_time){
68
+ Serial.print (" a second passed " );
69
+ Serial.print (s_time);Serial.print (" " );
70
+ Serial.print (my_time_client.get_millis (),3 );
71
+ Serial.println (" ms" );
72
+ s_last_time=s_time;
73
+
74
+ // please do not update too frequently
75
+ int8_t re=my_time_client.update ();
76
+ if (re==0 ){
77
+ Serial.println (" 0: sync but failed" );
78
+ delay (500 );
79
+ }else if (re==1 ){
80
+ Serial.println (" 1: sync and suc" );
81
+ }else if (re==2 ){
82
+ ;// Serial.println("2: not time to sync");
83
+ }else if (re==3 ){
84
+ Serial.println (" 3: last failed was just happen" );
85
+ }else {
86
+ Serial.print (" return value error: " );
87
+ Serial.println (re);
88
+ }
89
+ }
90
+
91
+ // float ms=my_time_client.get_millis();
92
+
93
+ delay (1 );
94
+ }
0 commit comments