macca-nz

no library time sync for ESP32

Aug 21st, 2023
1,186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 2.01 KB | Source Code | 0 0
  1. /*  For ESP32 Only
  2.     Open the Serial Monitor @ 115200bps
  3.     Time starts at zero epoch
  4.     The Flash/Boot button will invoke the serial input so you can sync to a current Unix Epoch
  5.     Change the "TZ_INFO" to your Zone so you get a local time conversion  */
  6.  
  7. define BTN 0
  8. #define TZ_INFO "NZST-12NZDT,M9.5.0,M4.1.0/3"     //for local time
  9.  
  10. bool pressed = 0, btnState, lastBtnState = 1, enableSerial = 0;
  11. uint32_t previousTime = 0;
  12. uint8_t lastSec;
  13.  
  14. void updateTime(void){              //This is the method to produce a
  15.     uint8_t sec = 0;                //Human readable clock in the Serial monitor
  16.     time_t now = time(NULL);
  17.     struct tm *now_tm;
  18.     now_tm = localtime(&now);
  19.     sec = now_tm->tm_sec;
  20.     if(lastSec != sec){
  21.             if(sec == 10 || sec == 20 || sec == 30 || sec == 40 || sec == 50){
  22.                 Serial.println(now_tm, "\n[UTC %z] %c\n");
  23.             }else{
  24.                 Serial.println(now_tm, "[%Z] Current Time %I:%M:%S [%p]");
  25.             }
  26.         lastSec = sec;
  27.     }
  28. }
  29.  
  30. void setup() {
  31.   Serial.begin(115200);
  32.   setenv("TZ", TZ_INFO, 1); tzset();  //Setup your Timezone for local time
  33. }
  34.  
  35. void loop() {
  36.      btnState = digitalRead(BTN);
  37.  
  38.     if(btnState != lastBtnState){
  39.       pressed = 1;
  40.       previousTime = millis();
  41.     }
  42.     if(millis() - previousTime >= 50){
  43.       if(pressed){
  44.         if(btnState == 0){
  45.           enableSerial = 1;
  46.           Serial.println("\n\rSerial is Waiting for a Unix Epoch Value\n\r");
  47.         }
  48.       }
  49.       pressed = 0;
  50.     }
  51.     if(enableSerial){
  52.       if(Serial.available() > 0){
  53.         String inString = Serial.readStringUntil('\n');
  54.         int32_t epoch = inString.toInt();
  55.         struct timeval tv = { .tv_sec = epoch };          //passing epoch to timeval
  56.         settimeofday(&tv, NULL);                          //sets the software RTC
  57.         enableSerial = 0;
  58.         Serial.println("\n\rSystem Human Readable Clock has been Updated\n\r");
  59.       }
  60.     }else{
  61.       updateTime();
  62.     }
  63.     lastBtnState = btnState;
  64. }
Tags: ESP32 time.h
Advertisement
Add Comment
Please, Sign In to add comment