/*
* Manually set human readable time on an ESP device
* Sketch will work on both ESP8266 and ESP32
* The idea of the sketch is to show how an EPOCH Unix time can be passed to
* the ESP's time function which is enabled by default when you select the board
* To do this you press the Flash/Boot button on the controller and enter the
* blocking "Serial Input" mode
* enter a valid EPOCH value and the system will sync to it.
* I have also changed the default 1/1/1970 Epoch to 1/1/2021 Midnight plus 2hrs 13min 20sec
* You need to chage the "TZ_INFO" line 18 to suit your timezone
* You can find the zone list here <https://github.com/nayarsystems/posix_tz_db/blob/master/zones.csv>
* get an "epoch" value here <https://www.epochconverter.com/>
*/
#if defined (ARDUINO_ARCH_ESP8266)
#include "sntp.h"
#endif
#define BTN 0
#define TZ_INFO "NZST-12NZDT,M9.5.0,M4.1.0/3" //for local time
int32_t epoch = (1609459200 + 8000); //1st Jan 2021 00:00:00 [UTC] + 2hrs 13min 20sec
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
char buf_t[80];
time_t t = time(NULL);
struct tm *now_tm;
now_tm = localtime(&t);
sec = now_tm->tm_sec;
if(lastSec != sec){
strftime(buf_t, 80, "\n[%Z][UTC %z] %c", now_tm);
Serial.println(buf_t);
lastSec = sec;
}
}
void setup() {
Serial.begin(115200);
setenv("TZ", TZ_INFO, 1); tzset(); //Setup your Timezone for local time
#if defined (ARDUINO_ARCH_ESP8266)
struct timeval _tv = {.tv_sec = epoch}; //passing epoch to timeval
settimeofday(&_tv, NULL);
Serial.println("\n\nESP8266 Epoch is Set and clock is starting\n");
#elif defined (ARDUINO_ARCH_ESP32)
struct timeval tv = {.tv_sec = epoch}; //passing epoch to timeval
settimeofday(&tv, NULL);
Serial.println("\n\nESP32 Epoch is Set and clock is starting\n");
#endif
}
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');
epoch = inString.toInt();
#if defined (ARDUINO_ARCH_ESP8266)
struct timeval _tv = {.tv_sec = epoch}; //passing epoch to timeval
settimeofday(&_tv, NULL);
#elif defined (ARDUINO_ARCH_ESP32)
struct timeval tv = {.tv_sec = epoch}; //passing epoch to timeval
settimeofday(&tv, NULL);
#endif
enableSerial = 0;
Serial.println("\n\rSystem Human Readable Clock has been Updated\n\r");
}
}else{
updateTime();
}
lastBtnState = btnState;
}