I have a project that is essentially a clock with some additional features. I am using an ESP8266 and and RTC to store the current time when the project is powered off. The ESP8266 connects to the Internet at startup using with WiFi. This all works fine, but I wanted to get the current time using NTP and synchronise the RTC to it. Eventually my plan is to add a radio clock to it to pick up the time signal from Anthorn. For now, I would like to get the time from NTP at startup. I found that using just one call to .update() in void startup() does not work. I experimented with various delays but did not find a reliable solution. I eventually found the following snippet online:
while(!timeClient.update()){
timeClient.forceUpdate();
}
So this is essentially if update() returns false, it will force an update until .update() succeeds. I have this within a statement that first sets up the WiFi:
// WiFi setup
Serial.print("MAC address: ");
Serial.println(WiFi.macAddress());
if (startWiFi(essid, psks)) {
ipaddr = WiFi.localIP();
Serial.print(F("IP address: "));
sprintf(ipaddrstr, "%d.%d.%d.%d", ipaddr[0], ipaddr[1], ipaddr[2], ipaddr[3]);
Serial.println(ipaddrstr);
// Get time from NTP server
timeClient.begin();
Serial.println(F("Getting time from NTP server..."));
while(!timeClient.update()){
timeClient.forceUpdate();
}
Serial.println(F("Done."));
NTPenabled = true;
getCurrentTimeStr(timeStr);
updateDisplayedTime(timeStr);
getCurrentDateStr(dateStr);
updateDisplayedDate(dateStr);
if (RTCenabled) updateRTCTime();
}else{
Serial.println(F("WiFi not connected!"));
}
At present, the code sends the status messages to serial to indicate whether it has succeeded or failed. These will eventually be removed or turned into debug messages which can be turned on or off. After the time has been updated via NTPclient, the program then proceeds to update the clock and display the current time.
This initially worked fine, but lately, it hangs quite frequently preventing the rest of the code from running. It is easy to see why because if timeClient.update() never returns true, the loop never ends and the messages show as follows:
20x4 display
MAC address: 44:17:93:10:F8:91
Starting WiFi client .......
IP address: 192.168.2.177
Getting time from NTP server...
The questions I have are why has it suddenly started failing? Was it a fortunate happenstance that I never saw it fail previously? Perhaps more importantly, is there a better to reliably check NTP time on startup before going into the main loop?