0

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
}



  • Arduino is resetting for some reason? – SBF Aug 19 at 9:45
  • 1
    But no other functions inside void set was repeated. If Arduino was resetting, everything inside setup should have repeated, right? – sunny_old_days Aug 19 at 9:54
  • i have this millis() function inside getNtpTime() and mainFunction(). any possibility of conflicts? – sunny_old_days Aug 19 at 9:59
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 suggestions – sunny_old_days Aug 19 at 12:02
  • try a little longer wait time – Juraj Aug 19 at 12:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.