Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Sketch will only do an NTP time update when you press the FLASH/BOOT button on the ESP32
- //On line 21 its worth getting an updated epoch value so when up compile and upload the system clock
- //will only be a couple of minutes slow https://www.epochconverter.com/
- #define TZ_INFO "EST5EDT,M3.2.0,M11.1.0" //EST/EDT UTC -5/-4
- //#define TZ_INFO "NZST-12NZDT,M9.5.0,M4.1.0/3" //NZST/NZDT UTC +12/+13
- #define BTN 0
- #include <WiFi.h>
- time_t now;
- //SSID and Password
- const char* ssid = "Your_ssid";
- const char* password = "Your_password";
- uint8_t lastSec;
- bool pressed = 0, lastBtnState = 1;
- uint32_t previousTime = 0;
- int32_t epoch = 1692574435; //get current epoch value here https://www.epochconverter.com/
- void updateTime(void){
- uint8_t sec = 0;
- 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){
- if(WiFi.status() != WL_CONNECTED){
- Serial.println(now_tm, "\n[WiFi is Disconnected]\n[UTC %z] %c\n");
- }else{
- Serial.println(now_tm, "\n[WiFi is Connected]\n[UTC %z] %c\n");
- }
- }else{
- Serial.println(now_tm, "[WiFi is Disconnected]\n[%Z] Current Time %I:%M:%S [%p]");
- }
- lastSec = sec;
- }
- }
- void NTPupdate(void){
- delay(500);
- Serial.printf("\nConnecting to WiFi %s ", ssid);
- WiFi.mode(WIFI_STA);
- WiFi.begin(ssid, password);
- WiFi.setAutoReconnect(false);
- while(WiFi.status() != WL_CONNECTED){Serial.print(".");delay(250);}
- Serial.print("\nIP address: ");Serial.println(WiFi.localIP());
- Serial.println("\nWiFi Connected.....");
- Serial.println("Getting NTP Time Update");
- now = time(nullptr);
- now = time(NULL);
- struct tm *now_tm;
- int64_t t = 0;
- while(t < epoch){
- t = time(&now);
- delay(500); //Small delay needed or we miss the packet
- }
- epoch = t;
- now_tm = localtime(&now);
- delay(1000);
- Serial.println(now_tm," NTP Sync Stamp %A, %B %d %Y %H:%M:%S [%Z]\n");
- lastSec = now_tm->tm_sec;
- if(WiFi.status() == WL_CONNECTED){
- WiFi.disconnect(true);
- WiFi.mode(WIFI_OFF);
- Serial.println(" [WiFi] Disconnected from WiFi and radio off!!\n");
- }
- }
- void setup(void) {
- Serial.begin(115200);
- while(!Serial);
- pinMode(BTN, INPUT);
- configTime(0, 0, "pool.ntp.org", "time.nist.gov"); //Configures 2 x NTP server address's
- setenv("TZ", TZ_INFO, 1); tzset(); //Setup your Timezone for true local time
- struct timeval tv = { .tv_sec = epoch };
- settimeofday(&tv, NULL);
- }
- void loop(void) {
- updateTime();
- bool btnState = digitalRead(BTN);
- if(btnState != lastBtnState){
- pressed = 1;
- previousTime = millis();
- }
- if(millis() - previousTime >= 50){
- if(pressed){
- if(btnState == 0){
- NTPupdate();
- }
- }
- pressed = 0;
- }
- lastBtnState = btnState;
- }
Advertisement
Add Comment
Please, Sign In to add comment