I've been building ucontroller projects for many years, but have only used simple 8 bit chips such as the AVR and related Arduino... Recently I have been expanding horizons to the ESP32 world using M5Stack components.
I'm sure that I am not the only maker who likes to build clocks - so of course my first ESP32 project will be a clock that takes advantage of WiFi and NTP synchronization. I've been doing a lot of research and searched the forums for my particular question, so apologies if this has been asked before (I really tried !)...
I've got the basics working - WiFi connected and NTP synch. My project includes a seconds display and will trigger a relay at some scheduled times during the day - so far, so good. I am using the standard Wifi.h and Time.h libraries as discussed in this video and this github.
I understand that these libraries will automatically resynch with NTP servers every hour without user intervention... As there is no 'background' task running, I assume that resynch is triggered when time() is called in my code. OK.
Question - based on initial observations, this 'resynch' is obtained rather quickly, but as with any network related topic I suspect there will be times when a network call to the NTP server takes a bit of time. Meanwhile, I'd like my display to show seconds updates uninterrupted and most important any scheduled tasks need to be timely.
Currently, I am saving the current second to a variable and using a while() loop that calls time() until the seconds have changed, at which point I update the display etc. But what happens if an NTP update is initiated in the library code while my delay loop is running? Is it possible that I miss a few seconds dur to the NTP call? The result would not only be the display looking odd, but potentially missing an event that is scheduled to the second.
I'm not certain if I am overthinking this or if I am handling things poorly - C++ is not really my coding strength.
Here is a sample of what my main loop looks like:
void loop() {
// getTimeReducedTraffic(3600);
auto t = time(nullptr);
auto tm = localtime(&t); // for local timezone.
getNTPtime(10);
showTime(timeinfo);
//delay(1000);
while (LastSecond == tm->tm_sec) {
// loop until next second
t = time(nullptr);
tm = localtime(&t); // for local timezone.
}
LastSecond = tm->tm_sec;
}
Thanks for any tips / suggestions!
EDIT - I have considered migrating to using the onboard RTC on my module for the primary source of time and synchronizing the RTC with NTP once or twice a day. While that may allow me to move the NTP update to less important time periods (ie overnight), technically would the seconds display still be thrown off if an NTP update is triggered? I think my primary misunderstanding is exactly how the NTP updates occur.