RTC and NTP sync

hy
hi I have a problem
i can not sync my rtc with ntp so that if the line falls the system keeps tracking time and seconds with RTC
It happens to me that every time you reset what is wrong?

void setup() 
{
  Serial.begin(9600);
  while (!Serial) ; // Needed for Leonardo only
  delay(250);

  pinMode(segmentClock, OUTPUT);
  pinMode(segmentData, OUTPUT);
  pinMode(segmentLatch, OUTPUT);

  digitalWrite(segmentClock, LOW);
  digitalWrite(segmentData, LOW);
  digitalWrite(segmentLatch, LOW);

 previousMillis = millis(); 

  
  Serial.println("Start Orologio collegamento in attesa ");
  if (Ethernet.begin(mac) == 0) {
  //  while (1) {
      Serial.println("Failed to configure Ethernet using DHCP");
      delay(10000);
  //  }
  }
  Serial.print("IP number assigned by DHCP is ");
  Serial.println(Ethernet.localIP());
  Udp.begin(localPort);
  Serial.println("waiting for sync");
  setSyncProvider(getNtpTime);
  
  if (connection != false) {
     //RTC.set(getNtpTime());
    // setTime(05, minute(), second(), 13, 2, 2009);   //set the system time to 23h31m30s on 13Feb2009
    // RTC.set(now());                     //set the RTC from the system time
   Serial.println("OK RTC");
   }else {
      
   Serial.println("RTC non sincronizzato"); 
   }
 

  setSyncInterval (timesyncro); 
 
 
}

//time_t prevDisplay = 0; // when the digital clock was displayed

void loop()
{ 
 
  if (connection=true) {
     setTime(hour(), minute(), second(), day(), month(), year());   //set the system time to 23h31m30s on 13Feb2009
     RTC.set(now());         
    }
  //  unsigned long currentMillis = millis();
  //  if((currentMillis - previousMillis > (interval * 3600000)) || (timeupdate == 1)) {
  //          previousMillis = currentMillis;
  //          Serial.print("PROVaaaaaaaaaaaaaaaaAAAAAAAAAAAAAAAAAAA ");
  //          Ethernet.maintain();
 //            setSyncProvider(getNtpTime);
     //       digitalClockDisplay();  

   // }    

 
//
tmElements_t tm;
     RTC.get;
      minuti = minute();
      ore = hour()*100;
      digitalClockDisplay();  
      delay (1000);
   showNumbersecondi(ore+minuti); //Test pattern
 
  
}

You have to post your entire code which includes references to any libraries you are using.
NTP will return an epoch time based on seconds elapsed since 1.1.1900 which is different to Arduino dateTime representation.
Are you going to display the time in your local timezone or in UTC ?

sorry
you list code with libraries

everything works
I can not set rtc with ntp.
I need this when the connection drops and it goes off

HELP ME

#include <DS3232RTC.h> 
#include <TimeLib.h>
#include <Ethernet2.h>
#include <EthernetUdp2.h>
#include <SPI.h>
#include <Wire.h>
 
//#include "RTClib.h"

//RTC_DS3231 rtc;

byte mac[] = {0x90, 0xA2, 0xDA, 0x10, 0xFC, 0x32};


IPAddress timeServer(193,204,114,232); // time-a.timefreq.bldrdoc.gov
int timesyncro =5;                   
unsigned long currentMillis = millis();

 
byte interval = 1; ;
//byte interval = 1; // interval of 1 hour = 3600000 , to check internet time
long previousMillis = 0;


const int timeZone = 1;     // Central European Time
//const int timeZone = -5;  // Eastern Standard Time (USA)
//const int timeZone = -4;  // Eastern Daylight Time (USA)
//const int timeZone = -8;  // Pacific Standard Time (USA)
//const int timeZone = -7;  // Pacific Daylight Time (USA)
unsigned long  ore, minuti,secondi,iniziale;
bool connection;

EthernetUDP Udp;
unsigned int localPort = 8888;  // local port to listen for UDP packets

//GPIO declarations per 7 segmenti
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
byte segmentClock = 6;
byte segmentLatch = 5;
byte segmentData = 7;
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 

void setup() 
{
  Serial.begin(9600);
  while (!Serial) ; // Needed for Leonardo only
  delay(250);

  pinMode(segmentClock, OUTPUT);
  pinMode(segmentData, OUTPUT);
  pinMode(segmentLatch, OUTPUT);

  digitalWrite(segmentClock, LOW);
  digitalWrite(segmentData, LOW);
  digitalWrite(segmentLatch, LOW);

 previousMillis = millis(); 

  
  Serial.println("Start Orologio collegamento in attesa ");
  if (Ethernet.begin(mac) == 0) {
  //  while (1) {
      Serial.println("Failed to configure Ethernet using DHCP");
      delay(10000);
  //  }
  }
  Serial.print("IP number assigned by DHCP is ");
  Serial.println(Ethernet.localIP());
  Udp.begin(localPort);
  Serial.println("waiting for sync");
  setSyncProvider(getNtpTime);
  
  if (connection != false) {
     //RTC.set(getNtpTime());
    // setTime(05, minute(), second(), 13, 2, 2009);   //set the system time to 23h31m30s on 13Feb2009
    // RTC.set(now());                     //set the RTC from the system time
   Serial.println("OK RTC");
   }else {
      
   Serial.println("RTC non sincronizzato"); 
   }
 

  setSyncInterval (timesyncro); 
 
 
}

//time_t prevDisplay = 0; // when the digital clock was displayed

void loop()
{ 
 
  if (connection=true) {
     setTime(hour(), minute(), second(), day(), month(), year());   //set the system time to 23h31m30s on 13Feb2009
     RTC.set(now());         
    }
  //  unsigned long currentMillis = millis();
  //  if((currentMillis - previousMillis > (interval * 3600000)) || (timeupdate == 1)) {
  //          previousMillis = currentMillis;
  //          Serial.print("PROVaaaaaaaaaaaaaaaaAAAAAAAAAAAAAAAAAAA ");
  //          Ethernet.maintain();
 //            setSyncProvider(getNtpTime);
     //       digitalClockDisplay();  

   // }    

 
//
tmElements_t tm;
     RTC.get;
      minuti = minute();
      ore = hour()*100;
      digitalClockDisplay();  
      delay (1000);
   showNumbersecondi(ore+minuti); //Test pattern
 
  
}

//Takes a number and displays 2 numbers. Displays absolute value (no negatives)
void showNumbersecondi(float value)
{
  int number = abs(value); //Remove negative signs and any decimals

  for (byte x = 0 ; x <4 ; x++)
  {
    int remainder = number % 10;

    postNumber(remainder, false);

    number /= 10;
  }

  //Latch the current segment data
  digitalWrite(segmentLatch, LOW);
  digitalWrite(segmentLatch, HIGH); //Register moves storage register on the rising edge of RCK
}

void showNumbersminuti(float value)
{
  int number = abs(value); //Remove negative signs and any decimals

  for (byte x = 0 ; x <4 ; x++)
  {
    int remainder = number % 10;

    postNumber(remainder, false);

    number /= 10;
  }

  //Latch the current segment data
  digitalWrite(segmentLatch, LOW);
  digitalWrite(segmentLatch, HIGH); //Register moves storage register on the rising edge of RCK
}



//Given a number, or '-', shifts it out to the display
void postNumber(byte number, boolean decimal)
{
  //    -  A
  //   / / F/B
  //    -  G
  //   / / E/C
  //    -. D/DP

#define a  1<<0
#define b  1<<6
#define c  1<<5
#define d  1<<4
#define e  1<<3
#define f  1<<1
#define g  1<<2
#define dp 1<<7

  byte segments;

  switch (number)
  {
    case 1: segments = b | c; break;
    case 2: segments = a | b | d | e | g; break;
    case 3: segments = a | b | c | d | g; break;
    case 4: segments = f | g | b | c; break;
    case 5: segments = a | f | g | c | d; break;
    case 6: segments = a | f | g | e | c | d; break;
    case 7: segments = a | b | c; break;
    case 8: segments = a | b | c | d | e | f | g; break;
    case 9: segments = a | b | c | d | f | g; break;
    case 0: segments = a | b | c | d | e | f; break;
    case ' ': segments = 0; break;
    case 'c': segments = g | e | d; break;
    case '-': segments = g; break;
  }

  if (decimal) segments |= dp;

  //Clock these bits out to the drivers
  for (byte x = 0 ; x < 8 ; x++)
  {
    digitalWrite(segmentClock, LOW);
    digitalWrite(segmentData, segments & 1 << (7 - x));
    digitalWrite(segmentClock, HIGH); //Data transfers to the register on the rising edge of SRCK
  }
}

Unless I'm missing something, you do not appear to be obtaining the NTP time anywhere in your code.
You have said "everything works" so I may not fully understand what is now in all those libraries you are using.

Clearly your code is expecting a function getNtpTime() and I would also have expected to see a reference to an NTP server eg "time.nist.gov" somewhere.

I suggest that you first make a separate sketch say based on https://www.arduino.cc/en/Tutorial/UdpNtpClient and print the time it obtains to the serial console. Once you have got that far, you can then begin to integrate the NTP code in your original sketch.

I am attaching the file that is called to the server with a timing per hour or every 5 seconds.

the problem is that if I turn off and on again the card, without connecting UTP, the time comes back to 1970 instead I expected to keep the recording inside RTC

void digitalClockDisplay(){
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year()); 
  Serial.println(); 
}

void printDigits(int digits){
  // utility for digital clock display: prints preceding colon and leading 0
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

/*-------- NTP code ----------*/

const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets

time_t getNtpTime()
{
  while (Udp.parsePacket() > 0) ; // discard any previously received packets
  Serial.println("Transmit NTP Request");
  connection = true;
  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 :-(");
  connection= false;
  return 0; // return 0 if unable to get the time
}

// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress &address)
{
  // set all bytes in the buffer to 0
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  // Initialize values needed to form NTP request
  // (see URL above for details on the packets)
  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum, or type of clock
  packetBuffer[2] = 6;     // Polling Interval
  packetBuffer[3] = 0xEC;  // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
  packetBuffer[12]  = 49;
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;
  // all NTP fields have been given values, now
  // you can send a packet requesting a timestamp:                 
  Udp.beginPacket(address, 123); //NTP requests are to port 123
  Udp.write(packetBuffer, NTP_PACKET_SIZE);
  Udp.endPacket();
}

You keep conjuring up more lumps of code.

I'd probably not do it like this using getNtpTime() :

setSyncProvider(getNtpTime);

setSyncProvider() synchronises the Arduino time library internal time with your time source such that you can , say, issue the command now() and get the current time.

I'd use the RTC as the primary time source here, not the NTP time. That means that when you start the Arduino, it shows the time from the RTC. So you'd have to have a function like say getRtcTime().

Every so often (say every 60 seconds) issue the command getNtpTime() to contact the time server and if the result looks plausible ( value returned and it is not zero etc.), then use that result to update the RTC (if necessary).

6v6gt:
I'd use the RTC as the primary time source here, not the NTP time. That means that when you start the Arduino, it shows the time from the RTC. So you'd have to have a function like say getRtcTime().

That is what "setSyncProvider()" does. If it syncs too often for your taste, use "setSyncInterval(interval)" to set the number of seconds between re-syncs.

johnwasser:
That is what "setSyncProvider()" does. If it syncs too often for your taste, use "setSyncInterval(interval)" to set the number of seconds between re-syncs.

What is the default interval? What interval is generally considered polite for most public NTP servers for general use? (To use after using a higher polling rate for code testing/development.)

OK but the issue here was neither the synchronisation frequency nor the synchronisation method. It was the primary time source.

The OP had a choice of two time sources. That is (a) an RTC and (b) a NTP server. The NTP server is more accurate but is not available at system start or when the internet connection fails. Therefore the suggestion to use the RTC as the primary times source together with the setSyncProvider() method to propagate it to the Arduino 'system time' instead of the NTP time source. However, when a valid NTP timestamp is available, that should be used to keep the RTC up to date. The RTC will then in turn keep the Arduino 'system time' up to date.

Of course there are also other ways of maintaining an accurate time using an Arduino.

ok
this is what I need to synchronize a rtc and ntp connection as soon as possible so that the NTP fall I have a defined time

i use
if (connection=true) {
setTime(hour(), minute(), second(), day(), month(), year()); //set the system time to 23h31m30s on 13Feb2009
RTC.set(now());
}

but not work

probably:

if (connection==true) {  // == not =

i correct but the problem is rtc

When i restart without NTP rtc is 1970 00:00

That's the Unix Time Epoch. Could your RTC be getting reset or power-cycled?

hy gfvalvo

tm.Hour = tm.Hour()* 100;

I work almost everything I have an error on this expression but I do not understand why.
You add me to make this multiply

tm.Hour is defined as a byte (max value 255).

Sembazuru:
What is the default interval?

From Time.cpp in the Time library:

static uint32_t syncInterval = 300;  // time sync will be attempted after this many seconds

That's five minutes.

Sembazuru:
What interval is generally considered polite for most public NTP servers for general use?

I would think that would depend on the server. Check the policy documents for the server you plan to use.

Bettybetty:

tm.Hour =  tm.Hour()* 100;

I work almost everything I have an error on this expression but I do not understand why.
You add me to make this multiply

I would think that “tm.Hour” would either be a variable or a function but not both at the same time.

johnwasser:
From Time.cpp in the Time library:

static uint32_t syncInterval = 300;  // time sync will be attempted after this many seconds

That’s five minutes.
I would think that would depend on the server. Check the policy documents for the server you plan to use.

I know this is an old thread, but I’m hoping this info helps someone who stumbles across it:

From the NIST Internet Time Servers web page:

“Whether you connect to a server using the name or the IP address, it is a bad practice to “hard-code” a particular server name or address into a device so that these parameters cannot be changed by the end user if that becomes necessary at some future time.”

Instead, you should use DNS to get the IP address that is assigned by time.nist.gov.

“All users should ensure that their software NEVER queries a server more frequently than once every 4 seconds. Systems that exceed this rate will be refused service. In extreme cases, systems that exceed this limit may be considered as attempting a denial-of-service attack.”

So don’t try to get the time from a NIST time server more than once every 4 seconds. If you do, you may get denied service or worse.

Here’s what I did, by adding some code to setup() in the TimeNTP example:

#include <TimeLib.h>
#include <Ethernet.h>
#include <DNS.h>
#include <EthernetUdp.h>
#include <SPI.h>
#include <Wire.h>
#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; 
// NTP Servers:
IPAddress timeServer(132, 163, 97, 1); // time-a-wwv.nist.gov
// IPAddress timeServer(132, 163, 97, 2); // time-b-wwv.nist.gov
// IPAddress timeServer(132, 163, 97, 3); // time-c-wwv.nist.gov


const int timeZone = -7;     // Arizona Time
//const int timeZone = -5;  // Eastern Standard Time (USA)
//const int timeZone = -4;  // Eastern Daylight Time (USA)
//const int timeZone = -8;  // Pacific Standard Time (USA)
//const int timeZone = -7;  // Pacific Daylight Time (USA)


EthernetUDP Udp;
unsigned int localPort = 8888;  // local port to listen for UDP packets


void setup() 
{
 Serial.begin(9600);
 while (!Serial) ; // Needed for Leonardo only
 delay(250);
 Serial.println("TimeNTP Example");
 if (Ethernet.begin(mac) == 0) {
   // no point in carrying on, so do nothing forevermore:
   while (1) {
     Serial.println("Failed to configure Ethernet using DHCP");
     delay(10000);
   }
 }
 Serial.print("Board IP number assigned by DHCP is ");
 Serial.println(Ethernet.localIP());
 Udp.begin(localPort);

 /* 
  * Maybe you could make a function using the following code, and call it whenever you need
  * to set your DS1307 using time from a NTP server.  But not more than once every 4 seconds!
  */

 /*
  * The following code attempts to get NIST to assign a Time Server IP address
  */
 int ret = 0;
 DNSClient dns;
 IPAddress remote_addr;
 
 dns.begin(Ethernet.dnsServerIP());
 ret = dns.getHostByName("time.nist.gov", remote_addr);
 if (ret == 1) {
     Serial.print("Time Server IP: ");
     Serial.println(remote_addr);
     timeServer = remote_addr;
 }
 else
 {
   Serial.println("getHostByName failed to get Time Server IP address using time.nist.gov");
   Serial.print("ret = ");
   Serial.println(ret);
 }
 /* end of code to get NIST to assign Time Server IP address */
  
 Serial.println("waiting for sync");
 setSyncProvider(getNtpTime);
 
 /* 
  *  The following three lines of code set the DS1307 to time retrieved from the NTP server
  *  and switch the time sync provider over to the DS1307.  Warning:  No error checking performed.
  */
 RTC.set(now());   // set the RTC and the system time to the received value
 setTime(now()); 
 setSyncProvider(RTC.get);   // the function to get the time from the RTC
}

This code only gets the time from the NIST time servers and sets the DS1307 time once during setup, but hopefully you’ll get an idea of how it could work for you.

Looks interesting but aren't NIST servers only a subset of all NTP capable servers ?

I just tried a ping to the address time.nist.gov

C:\Users\6v6gt>
C:\Users\6v6gt>ping time.nist.gov

Pinging ntp1.glb.nist.gov [2610:20:6f97:97::4] with 32 bytes of data:
Reply from 2610:20:6f97:97::4: time=138ms
Reply from 2610:20:6f97:97::4: time=135ms
Reply from 2610:20:6f97:97::4: time=144ms
Reply from 2610:20:6f97:97::4: time=134ms

Ping statistics for 2610:20:6f97:97::4:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 134ms, Maximum = 144ms, Average = 137ms

C:\Users\6v6gt>
C:\Users\6v6gt>
C:\Users\6v6gt>
C:\Users\6v6gt>ping 0.ch.pool.ntp.org

Pinging 0.ch.pool.ntp.org [178.209.50.229] with 32 bytes of data:
Reply from 178.209.50.229: bytes=32 time=14ms TTL=51
Reply from 178.209.50.229: bytes=32 time=10ms TTL=51
Reply from 178.209.50.229: bytes=32 time=16ms TTL=51
Reply from 178.209.50.229: bytes=32 time=17ms TTL=51

Ping statistics for 178.209.50.229:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 10ms, Maximum = 17ms, Average = 14ms

C:\Users\6v6gt>

At least with ping, network access looks a little slow compared with a sample local NTP server.

CF20852:
Here’s what I did, by adding some code to setup() in the TimeNTP example:

When i do this, I get a time that is completely wrong! My time and date comes back as 2066. Any ideas why this might be?

Here’s my code:

#include <TimeLib.h>
#include <Ethernet.h>
#include <DNS.h>
#include <EthernetUdp.h>
#include <SPI.h>
#include <Wire.h>
#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// NTP Servers:
IPAddress timeServer(132, 163, 97, 1); // time-a-wwv.nist.gov
// IPAddress timeServer(132, 163, 97, 2); // time-b-wwv.nist.gov
// IPAddress timeServer(132, 163, 97, 3); // time-c-wwv.nist.gov


const int timeZone = +0;     // Arizona Time
//const int timeZone = -5;  // Eastern Standard Time (USA)
//const int timeZone = -4;  // Eastern Daylight Time (USA)
//const int timeZone = -8;  // Pacific Standard Time (USA)
//const int timeZone = -7;  // Pacific Daylight Time (USA)


EthernetUDP Udp;
unsigned int localPort = 8888;  // local port to listen for UDP packets


void setup()
{
 Serial.begin(9600);
 while (!Serial) ; // Needed for Leonardo only
 delay(250);
 Serial.println("TimeNTP Example");
 if (Ethernet.begin(mac) == 0) {
   // no point in carrying on, so do nothing forevermore:
   while (1) {
     Serial.println("Failed to configure Ethernet using DHCP");
     delay(10000);
   }
 }
 Serial.print("Board IP number assigned by DHCP is ");
 Serial.println(Ethernet.localIP());
 Udp.begin(localPort);

 /*
  * Maybe you could make a function using the following code, and call it whenever you need
  * to set your DS1307 using time from a NTP server.  But not more than once every 4 seconds!
  */

 /*
  * The following code attempts to get NIST to assign a Time Server IP address
  */
 int ret = 0;
 DNSClient dns;
 IPAddress remote_addr;
 
 dns.begin(Ethernet.dnsServerIP());
 ret = dns.getHostByName("time.nist.gov", remote_addr);
 if (ret == 1) {
     Serial.print("Time Server IP: ");
     Serial.println(remote_addr);
     timeServer = remote_addr;
 }
 else
 {
   Serial.println("getHostByName failed to get Time Server IP address using time.nist.gov");
   Serial.print("ret = ");
   Serial.println(ret);
 }
 /* end of code to get NIST to assign Time Server IP address */
  
 Serial.println("waiting for sync");
 setSyncProvider(getNtpTime);
 
 /*
  *  The following three lines of code set the DS1307 to time retrieved from the NTP server
  *  and switch the time sync provider over to the DS1307.  Warning:  No error checking performed.
  */
 RTC.set(now());   // set the RTC and the system time to the received value
 setTime(now());
 setSyncProvider(RTC.get);   // the function to get the time from the RTC
}
void loop()
{  

      digitalClockDisplay();  
delay(1000);
}

void digitalClockDisplay(){
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year()); 
  Serial.println(); 
}

void printDigits(int digits){
  // utility for digital clock display: prints preceding colon and leading 0
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

/*-------- NTP code ----------*/

const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets

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
}

// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress &address)
{
  // set all bytes in the buffer to 0
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  // Initialize values needed to form NTP request
  // (see URL above for details on the packets)
  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum, or type of clock
  packetBuffer[2] = 6;     // Polling Interval
  packetBuffer[3] = 0xEC;  // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
  packetBuffer[12]  = 49;
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;
  // all NTP fields have been given values, now
  // you can send a packet requesting a timestamp:                 
  Udp.beginPacket(address, 123); //NTP requests are to port 123
  Udp.write(packetBuffer, NTP_PACKET_SIZE);
  Udp.endPacket();
}

thanks in advance!