Advertisement
TolentinoCotesta

ESP8266 NTP Sync

Apr 8th, 2018
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.37 KB | None | 0 0
  1. #include <ESP8266WiFi.h>
  2. #include <time.h>
  3. #define TIMEZONE        1       // (UTC+) Standard TimeZone in hours
  4. #define DST          3600       // Daily summer time offset in seconds
  5.  
  6. const char* ssid = "********";
  7. const char* password = "*********";
  8.  
  9. unsigned long updateTime = millis();
  10.  
  11. void setup() {
  12.   // Start Serial for debug
  13.   Serial.begin(115200);
  14.   Serial.println();
  15.   Serial.println(F("Sync NTP server example."));
  16.  
  17.   WiFi.mode(WIFI_STA);  
  18.   // attempt to connect to Wifi network:
  19.   Serial.print("Connecting Wifi: ");
  20.   Serial.println(ssid);
  21.   WiFi.begin(ssid, password);
  22.   while (WiFi.status() != WL_CONNECTED) {
  23.     Serial.print(".");
  24.     delay(500);
  25.   }
  26.  
  27.   Serial.println("");
  28.   Serial.println("WiFi connected");
  29.   Serial.print("IP address: ");
  30.   Serial.println(WiFi.localIP());
  31.  
  32.   // Sync system time with one of up to 3 NTP servers (after connected)
  33.   configTime(TIMEZONE * 3600, DST, "pool.ntp.org", "time.google.com", "time.windows.com");
  34. }
  35.  
  36.  
  37. void loop() {    
  38.   if (millis() - updateTime > 5000) {        
  39.     // time() return the actual Unix "epoch" time (number of seconds that have elapsed since January 1, 1970)
  40.     time_t now = time(nullptr);
  41.     Serial.printf("\n\nEpoch Unix time: %ul", now );
  42.     Serial.printf("\nHuman readable time: %s", ctime(&now));
  43.    
  44.     // with the already defined struct "tm" we can easy have access at days, hours, minutes etc etc etc
  45.     // tm_sec The number of seconds after the minute, normally in the range 0 to 59
  46.     // tm_min The number of minutes after the hour, in the range 0 to 59.
  47.     // tm_hour The number of hours past midnight, in the range 0 to 23.
  48.     // tm_mday The day of the month, in the range 1 to 31.
  49.     // tm_mon The number of months since January, in the range 0 to 11.
  50.     // tm_year The number of years since 1900.
  51.     // tm_wday The number of days since Sunday, in the range 0 to 6.
  52.     // tm_yday The number of days since January 1, in the range 0 to 365.
  53.  
  54.     // create local instance of "tm"
  55.     struct tm lTime;
  56.     // fill the structure data with actual time  
  57.     localtime_r(&now, &lTime);          
  58.  
  59.     // print out data
  60.     Serial.printf("\nDate: %02d/%02d/%04d", lTime.tm_mday, lTime.tm_mon +1 , lTime.tm_year + 1900);          
  61.     Serial.printf("\nTime: %02d:%02d:%02d", lTime.tm_hour, lTime.tm_min, lTime.tm_sec);    
  62.    
  63.     updateTime = millis();
  64.   }
  65.  
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement