macca-nz

ESP32/8266 ezTime Simple Custom Clock

Apr 26th, 2023 (edited)
822
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  * This Sketch uses ezTime library to create a Serial monitor NTP clock
  3.  * It is the bare minimum needed to do local time use NTP
  4.  * The default NTP resync period of ezTime is 30 minutes
  5.  * It prints a simple "Local Time" for seconds 1 to 9
  6.  * On the minute a full default Time Stamp is printed
  7.  *
  8.  * Provide official timezone names
  9.  * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
  10.  *
  11.  * NOTE: Only tested on ESP32
  12.  */
  13.  
  14. #include <ezTime.h>               //Library to use our system clock for NTP time
  15.  
  16. #if defined (ESP32)               //Lets the compiler work with
  17.     #include <WiFi.h>             //ESP32
  18. #elif defined (ESP8266)           //or
  19.     #include <ESP8266WiFi.h>      //ESP8266 without changing any script
  20. #endif
  21.  
  22. Timezone myTZ;                    //Creates our Timezone object to get "Local Time"
  23.  
  24. const char* ssid = "Your_ssid";            
  25. const char* password = "Your_password";  
  26.  
  27. int lastSec;
  28.  
  29. String getMyTime(){             //Custom Clock Display
  30.     char buf[22];
  31.     String mT = "";
  32.     sprintf(buf, "Local Time  %02u:%02u:%02u", myTZ.hour(), myTZ.minute(), myTZ.second());
  33.     mT += buf;
  34.     return mT;
  35. }
  36.  
  37. void setup() {
  38.     Serial.begin(115200);while(!Serial){;}
  39.     WiFi.begin(ssid, password);
  40.     while(WiFi.status() != WL_CONNECTED);
  41.     waitForSync();                          //Default method for NTP sync every 30min
  42.     myTZ.setLocation(F("Pacific/Auckland"));//Sets our Timezone object
  43.     lastSec = myTZ.second();
  44. }
  45.  
  46. void loop() {
  47.     events();                       //Needed to run the NTP setup method
  48.     if(myTZ.second() != lastSec){
  49.         lastSec = myTZ.second();
  50.             if(myTZ.second() != 0){
  51.                 String myTime = getMyTime();
  52.                 Serial.println(myTime);         //Use's the Custom Clock Display
  53.             }else{
  54.                 Serial.println("\n" + myTZ.dateTime() + "\n");
  55.             }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment