I am trying to time sync my arduino hardware to NTP server. I have a `setSyncProvider(getNtpTime) ́ function to do it and called inside the void setup. I have another function (mainFunction) inside the main loop, that calls every minute. I have added a function to display time inside this mainFunction so that time will update every minutes. Code works fine for first five minutes. Then it calls the getNtpTime again even though it is not inside the loop. Why is it happening?
time_t getNtpTime()
{
while (Udp.parsePacket() > 0) ; // discard any previously received packets
Serial.println("Transmit NTP Request");
sendNTPpacket(timeServer);
uint32_t beginWait = millis();
while (millis() - beginWait < 1500) {
int size = Udp.parsePacket();
if (size >= NTP_PACKET_SIZE) {
Serial.println("Receive NTP Response");
Udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer
unsigned long secsSince1900;
// convert four bytes starting at location 40 to a long integer
secsSince1900 = (unsigned long)packetBuffer[40] << 24;
secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
secsSince1900 |= (unsigned long)packetBuffer[43];
return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
}
}
Serial.println("No NTP Response :-(");
return 0; // return 0 if unable to get the time
}
1 Answer 1
The setSyncProvider
function of the TimeLib sets a function which will be called by the library every interval
seconds. The interval
is set with setSyncInterval
. Default interval is 300 seconds.
-
I checked the time of calls in serial monitor. As i mentioned in the question, my main loop has a function that calls every minute. in the main loop getNtpTime called at 360.8 second and then at 660.8. After first call, there was no display error. But after second call, there was display error. Display returned to normal in the next minute and the above cycle of error repeated. That means 3rd call was fine, 4 gives error. 5th was fine, 6th gives error! Any suggestionsmaster_yoda– master_yoda2019年08月19日 12:02:13 +00:00Commented Aug 19, 2019 at 12:02
-
try a little longer wait time2019年08月19日 12:21:59 +00:00Commented Aug 19, 2019 at 12:21
millis()
function insidegetNtpTime()
andmainFunction()
. any possibility of conflicts?