macca-nz

ESP32/8266 time with Arduino TimeLib

Apr 27th, 2023 (edited)
777
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  * This sketch has been tested to work on both
  3.  * ESP32 (Arduino Board Profile V2.0.8) and ESP8266 (Arduino Board Profile V3.1.2)
  4.  *
  5.  * It provide you with a simple NTP Clock working in the following order
  6.  * > Connect to WiFi
  7.  * > Set TimeZone and Get local local time (Note: local time is in tm elements format at this point)
  8.  * > Do a "strftime" detailed time stamp
  9.  * > Convert local time "tmelements" to a "Local Time Unix Epoch" value using "mktime"
  10.  * > Use to set the Arduino "TimeLib.h" library
  11.  * > Use "Local Time Unix Epoch" to "setTime()" in "TimeLib.h"
  12.  * > Create a one second and one minute task
  13.  * > Disconnect and turn off WiFi
  14.  * > Task #1 Simple Custom Serial Print Time Stamp every second using TimeLib functions
  15.  * > Task #2 On the minute rollover repeat the time sync routine
  16.  *
  17.  * Under normal use NTP time updates would only be needed a few times a day or even once a day
  18.  *
  19.  * See https://github.com/nayarsystems/posix_tz_db/blob/master/zones.csv for Timezone codes for your region
  20.  *
  21.  */
  22.  
  23. #if defined (ESP32)                           // Auto detect ESP Chip type
  24.     #include <WiFi.h>
  25. #elif defined (ESP8266)
  26.     #include <ESP8266WiFi.h>    
  27. #endif
  28.  
  29. #include <sys/time.h>                         // C#/C++ time library
  30. #include <TimeLib.h>                          // Arduino Time Library
  31.  
  32. #define TZ_INFO "NZST-12NZDT,M9.5.0,M4.1.0/3" // Timezone string
  33. const char* ntpServer = "pool.ntp.org";       // All that's needed to connect to NTP server pools
  34.  
  35. const char* ssid       = "Your_ssid";
  36. const char* password   = "Your_password";
  37.  
  38. uint8_t count = 0, syncMin, lastSec;          // A few variables for time tasks
  39.  
  40. time_t tmConvert_t(int YYYY, byte MM, byte DD, byte hh, byte mm, byte ss){
  41.   tmElements_t tmSet;
  42.   tmSet.Year = YYYY;
  43.   tmSet.Month = MM;                           // This function makes our local epoch value
  44.   tmSet.Day = DD;
  45.   tmSet.Hour = hh;
  46.   tmSet.Minute = mm;
  47.   tmSet.Second = ss;
  48.   return makeTime(tmSet);
  49. }
  50.  
  51. void setMyClock(void){
  52.     int yr, mo, dy, hr, mn, sc;
  53.     time_t now = time(NULL);
  54.     struct tm *now_tm;
  55.     now_tm = localtime(&now);
  56.     sc = now_tm->tm_sec;
  57.     mn = now_tm->tm_min;
  58.     hr = now_tm->tm_hour;
  59.     yr = now_tm->tm_year -70;
  60.     mo = now_tm->tm_mon +1;
  61.     dy = now_tm->tm_mday;
  62.     int32_t epoch = tmConvert_t(yr,mo,dy,hr,mn,sc);
  63.     setTime(epoch);
  64.     syncMin = minute();
  65.     lastSec = second();
  66.     Serial.println("Clock Set\n");
  67.     return;
  68. }
  69.  
  70. void getLocalTime(void){
  71.   time_t now = time(nullptr);
  72.   struct tm *now_tm;
  73.   now = time(NULL);
  74.   while(now_tm != localtime(&now)){now_tm = localtime(&now);}
  75.   //Serial.println(now_tm, "%A, %B %d %Y %H:%M:%S [%Z]");      //This can be used on ESP32 if preferred
  76.   char buffer [80];
  77.   strftime (buffer,80,"%A, %B %d %Y %H:%M:%S [%Z]",now_tm);
  78.   Serial.println(buffer);
  79.   return;
  80. }
  81.  
  82. void doWiFi(void){
  83.   //connect to WiFi
  84.   delay(200);
  85.   Serial.printf("\nConnecting to %s ", ssid);
  86.   WiFi.begin(ssid, password);
  87.   while (WiFi.status() != WL_CONNECTED) {
  88.       delay(500);
  89.       Serial.print(".");
  90.   }
  91.   Serial.println(" WiFi now Connected\n");
  92.   getLocalTime();
  93.   //disconnect WiFi as it's no longer needed
  94.   WiFi.disconnect(true);
  95.   WiFi.mode(WIFI_OFF);
  96.   Serial.println("WiFi is Disconnected");
  97. }
  98.  
  99. void myClock(void){
  100.     char buff[50];
  101.     sprintf(buff,"My Clock Time %02d:%02d:%02d  Date: %02d/%02d/%d", hour(),minute(),second(),day(),month(),year());
  102.     Serial.println(buff);
  103.     Serial.println("");
  104.     return;
  105. }
  106.  
  107. void setup(){
  108.   Serial.begin(115200);
  109.   configTime(0, 0, ntpServer);
  110.   setenv("TZ", TZ_INFO, 1);
  111.   tzset();
  112.   doWiFi();
  113.   setMyClock();
  114. }
  115.  
  116. void loop(){
  117.   if(lastSec != second()){
  118.     myClock();
  119.     lastSec = second();
  120.         if(syncMin != minute()){
  121.             doWiFi();
  122.             setMyClock();
  123.         }
  124.   }
  125. }
Advertisement
Add Comment
Please, Sign In to add comment