I have the following code which is getting the time from NTP just fine. My project when complete with all other functions is to sleep for 20 minutes and then wake up, check sensors / perform needed actions and go back to sleep. I have had issues with the NTP time drifting a lot and want to know how I can get the time to update via a command. I am thinking on having it update after every 3rd or 4th boot.
Any help on what the command is to repoll the ntp would be appreciated. I suspect if my project didn't go to sleep it would keep more accurate time and probably poll the NTP as required but as my project goes to sleep it is probably missing these intervals. I have tried various commands in loops with some possibly being a bit successful but nothing was consistent.
Any help would be appreciated. To clarify I am doing this in Arduino IDE with ESP32 Core 2.0.4
My code is as follows
Code: Select all
#include <WiFi.h>
#include <esp_sntp.h>
#define uS_TO_S_FACTOR 1000000
#define TIME_TO_SLEEP 20 //This is 20seconds for the purposes of troubleshooting. Once working will be 20 minutes (1200)
RTC_DATA_ATTR long bootcnt = 0;
RTC_DATA_ATTR long ClockCnt = 0;
long startTime;
const char* ssid = "myssid";
const char* password = "myPassword";
const char* ntpServer = "pool.ntp.org";
const char* TZ_INFO = "EST-10EDT-11,M10.1.0/02:00:00,M4.1.0/03:00:00";
void TimeCalcs()
{
struct tm time;
configTime(0, 3600, ntpServer);
setenv("TZ", TZ_INFO, 1);
if(!getLocalTime(&time))
{
Serial.println("Could not obtain time info");
return;
}
Serial.print("Current Time: "); Serial.println(asctime(&time));
Serial.print("---------\n");
if (ClockCnt > 3)
{
//Want code here to repoll the NTP. Have tried configTime, getLocalTime($time), sntp_init(), among others
delay(500);
ClockCnt = 0;
} else
{
ClockCnt++;
Serial.println("ClockCnt: " + String(ClockCnt));
}
}
void setup()
{
Serial.begin(115200);
bootcnt++;
Serial.println("Boot Count: " + String(bootcnt));
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
WiFi.begin(ssid, password);
startTime = millis();
while (WiFi.status() != WL_CONNECTED && (millis() - startTime) <= 8000) // try for 8 seconds
{
delay(500);
Serial.print(".");
}
if (WiFi.status() != WL_CONNECTED)
{
Serial.print("\nWiFi failed to Connect\n");
} else
{
Serial.print("\nWiFi Connected\n");
}
sntp_set_time_sync_notification_cb(timeSyncCallback);
TimeCalcs();
delay(500);
Serial.println("Going to sleep");
Serial.flush();
delay(1000); //Added as per advice on forum. With this had about 5 seconds in 12 hours
esp_deep_sleep_start(); //Anything after this will never run
}
void timeSyncCallback(struct timeval *tv)
{
Serial.println("\n----Time Sync----- Time should have been verified and updated if needed");
Serial.println(tv->tv_sec);
Serial.println(ctime(&tv->tv_sec));
}
void loop()
{
Serial.print("Code here should never run");
}