Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* For ESP32 Only
- Open the Serial Monitor @ 115200bps
- Time starts at zero epoch
- The Flash/Boot button will invoke the serial input so you can sync to a current Unix Epoch
- Change the "TZ_INFO" to your Zone so you get a local time conversion */
- define BTN 0
- #define TZ_INFO "NZST-12NZDT,M9.5.0,M4.1.0/3" //for local time
- bool pressed = 0, btnState, lastBtnState = 1, enableSerial = 0;
- uint32_t previousTime = 0;
- uint8_t lastSec;
- void updateTime(void){ //This is the method to produce a
- uint8_t sec = 0; //Human readable clock in the Serial monitor
- time_t now = time(NULL);
- struct tm *now_tm;
- now_tm = localtime(&now);
- sec = now_tm->tm_sec;
- if(lastSec != sec){
- if(sec == 10 || sec == 20 || sec == 30 || sec == 40 || sec == 50){
- Serial.println(now_tm, "\n[UTC %z] %c\n");
- }else{
- Serial.println(now_tm, "[%Z] Current Time %I:%M:%S [%p]");
- }
- lastSec = sec;
- }
- }
- void setup() {
- Serial.begin(115200);
- setenv("TZ", TZ_INFO, 1); tzset(); //Setup your Timezone for local time
- }
- void loop() {
- btnState = digitalRead(BTN);
- if(btnState != lastBtnState){
- pressed = 1;
- previousTime = millis();
- }
- if(millis() - previousTime >= 50){
- if(pressed){
- if(btnState == 0){
- enableSerial = 1;
- Serial.println("\n\rSerial is Waiting for a Unix Epoch Value\n\r");
- }
- }
- pressed = 0;
- }
- if(enableSerial){
- if(Serial.available() > 0){
- String inString = Serial.readStringUntil('\n');
- int32_t epoch = inString.toInt();
- struct timeval tv = { .tv_sec = epoch }; //passing epoch to timeval
- settimeofday(&tv, NULL); //sets the software RTC
- enableSerial = 0;
- Serial.println("\n\rSystem Human Readable Clock has been Updated\n\r");
- }
- }else{
- updateTime();
- }
- lastBtnState = btnState;
- }
Advertisement
Add Comment
Please, Sign In to add comment