[solved]NTP date and time updating but serial sais update is failed

Hi,

I have a problem with ntp update. However the date and time values are saved to the sd card, when sketch is running serial sais: ntp server update failed.
I am not using any rtc.
Thanks for any help.

//Timeserver declaration
IPAddress timeServer(xx, x, xx, xx);
const long timeZoneOffset = 3600L;  
unsigned int localPort = 8888;
const int NTP_PACKET_SIZE= 48;      
byte packetBuffer[NTP_PACKET_SIZE];  
EthernetUDP Udp;                    
unsigned long ntpLastUpdate = 0;    
time_t prevDisplay = 0;    
...
...
//**in the setup() after getting IP address

//Try to get the date and time 
   int trys=0;
   while(!getTimeAndDate() && trys<10) {
     trys++;
   }
...

//**at the end of the setup()

int getTimeAndDate() {
   int flag=0;
   Udp.begin(localPort);
   sendNTPpacket(timeServer);
   delay(1000);
   if (Udp.parsePacket()){
     Udp.read(packetBuffer,NTP_PACKET_SIZE);  // read the packet into the buffer
     unsigned long highWord, lowWord, epoch;
     highWord = word(packetBuffer[40], packetBuffer[41]);
     lowWord = word(packetBuffer[42], packetBuffer[43]);  
     epoch = highWord << 16 | lowWord;
     epoch = epoch - 2208988800 + timeZoneOffset;
     flag=1;
     setTime(epoch);
     ntpLastUpdate = now();
   }
   return flag;
}
 
unsigned long sendNTPpacket(IPAddress& address)
{
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  packetBuffer[0] = 0b11100011;
  packetBuffer[1] = 0;
  packetBuffer[2] = 6;
  packetBuffer[3] = 0xEC;
  packetBuffer[12]  = 49;
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;                  
  Udp.beginPacket(address, 123);
  Udp.write(packetBuffer,NTP_PACKET_SIZE);
  Udp.endPacket();
}
 
// Clock display of the time and date
void clockDisplay(){
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year());
  Serial.println();
}
 
// Utility function for clock display: prints preceding colon and leading 0
void printDigits(int digits){
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

//**in the loop()

//NTP update
{
      int trys=0;
      while(!getTimeAndDate() && trys<10){
        trys++;
      }
      if(trys<10){
        Serial.println("ntp server update success");
      }
      else{
        Serial.println("ntp server update failed");
      }
    }
    // Display the time if it has changed by more than a second.
    if( now() != prevDisplay)
   {
    prevDisplay = now();
    clockDisplay();  
    }
....
//** and after sending the values to SDcard

I use Ethernet.begin just once in the setup() function, and I also use the Udp.begin just one in the setup() function.

That is the same in my code...no duplicate ethernet.begin and udp.begin...

vespapierre:
That is the same in my code...no duplicate ethernet.begin and udp.begin...

Are you not seeing this?

int getTimeAndDate() {
   int flag=0;
// This is Udp.begin again and again and again...
   Udp.begin(localPort);
   sendNTPpacket(timeServer);

Next time post all your code, not just snippets.

The "xx, x, xx, xx" is not your real sketch I hope ?
Can you tell which public time servers you have tried ?

SurferTim,

thanks for warning! I have moved out Udp.begin(localPort); from getTimeAndDate to just right after getting the IP address.
Sorry for not posting the whole code, only reason is I did not want to post such sensor readings.
I will back with the results.

Caltoa,

of course! Timeserver is 84.2.46.19

XDThis is a bit ambiguous. It may be doing a NOT of (getTimeAndDate() && trys<10)

      while(!getTimeAndDate() && trys<10){
        trys++;
      }

Try this instead.

      while((!getTimeAndDate()) && trys<10){
        trys++;
      }

edit: Also add a serial print to see if it is going through this while loop.

      while((!getTimeAndDate()) && trys<10){
        Serial.println("get time failed");
        trys++;
      }

Hi,

again many thanks for the help! Update is Success now!

Hi people... I am really new on these kind of things but it seems that we have found the same code. I found this code on another forum and was trying it.... but i did not manage to fix the problem... it keeps telling me that ntp server failed to update. here is the code as well.... can anyone tell me what is my problem?

#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <Time.h>

/* ******** Ethernet Card Settings ******** */
// Set this to your Ethernet Card Mac Address
byte mac[] = { 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF }; 

/* ******** NTP Server Settings ******** */
/* us.pool.ntp.org NTP server 
   (Set to your time server of choice) */
IPAddress timeServer(192, 164, 127, 6); 

/* Set this to the offset (in seconds) to your local time
   This example is GMT - 6 */
const long timeZoneOffset = -21600L;   

/* Syncs to NTP server every 15 seconds for testing, 
   set to 1 hour or more to be reasonable */
unsigned int ntpSyncTime = 15;         


/* ALTER THESE VARIABLES AT YOUR OWN RISK */
// local port to listen for UDP packets
unsigned int localPort = 8888;
// NTP time stamp is in the first 48 bytes of the message
const int NTP_PACKET_SIZE= 48;      
// Buffer to hold incoming and outgoing packets
byte packetBuffer[NTP_PACKET_SIZE];  
// A UDP instance to let us send and receive packets over UDP
EthernetUDP Udp;                    
// Keeps track of how long ago we updated the NTP server
unsigned long ntpLastUpdate = 0;    
// Check last time clock displayed (Not in Production)
time_t prevDisplay = 0;             

void setup() {
   Serial.begin(9600);
   
   // Ethernet shield and NTP setup
   int i = 0;
   int DHCP = 0;
   DHCP = Ethernet.begin(mac);
   //Try to get dhcp settings 30 times before giving up
   while( DHCP == 0 && i < 30){
     delay(1000);
     DHCP = Ethernet.begin(mac);
     i++;
   }
   if(!DHCP){
    Serial.println("DHCP FAILED");
     for(;;); //Infinite loop because DHCP Failed
   }
   Serial.println("DHCP Success");
    //Try to get the date and time
   int trys=0;
   while(!getTimeAndDate() && trys<10)
   {
     Serial.println("get time failed!");
     trys++;
   }
}

// Do not alter this function, it is used by the system
int getTimeAndDate() {
   int flag=0;
   Udp.begin(localPort);
   sendNTPpacket(timeServer);
   delay(1000);
   if (Udp.parsePacket()){
     Udp.read(packetBuffer,NTP_PACKET_SIZE);  // read the packet into the buffer
     unsigned long highWord, lowWord, epoch;
     highWord = word(packetBuffer[40], packetBuffer[41]);
     lowWord = word(packetBuffer[42], packetBuffer[43]);  
     epoch = highWord << 16 | lowWord;
     epoch = epoch - 2208988800 + timeZoneOffset;
     flag=1;
     setTime(epoch);
     ntpLastUpdate = now();
   }
   return flag;
}

// Do not alter this function, it is used by the system
unsigned long sendNTPpacket(IPAddress& address)
{
  memset(packetBuffer, 0, NTP_PACKET_SIZE); 
  packetBuffer[0] = 0b11100011;
  packetBuffer[1] = 0;
  packetBuffer[2] = 6;
  packetBuffer[3] = 0xEC;
  packetBuffer[12]  = 49; 
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;		   
  Udp.beginPacket(address, 123);
  Udp.write(packetBuffer,NTP_PACKET_SIZE);
  Udp.endPacket(); 
}

// Clock display of the time and date (Basic)
void clockDisplay(){
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year()); 
  Serial.println(); 
}

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

// This is where all the magic happens...
void loop() {
    // Update the time via NTP server as often as the time you set at the top
    if(now()-ntpLastUpdate > ntpSyncTime) {
      int trys=0;
      while(!getTimeAndDate() && trys<10){
        trys++;
      }
      if(trys<10){
        Serial.println("ntp server update success");
      }
      else{
        Serial.println("ntp server update failed");
      }
    }
    
    // Display the time if it has changed by more than a second.
    if( now() != prevDisplay){
      prevDisplay = now();
      clockDisplay();  
    }
}

hi,

decalaration at the begining:

//Timeserver
IPAddress timeServer(xx, xx, xx, xx); (here u should put your local timeserver, google it out )
const long timeZoneOffset = 3600L;  
unsigned int localPort = 8888;
const int NTP_PACKET_SIZE= 48;      
byte packetBuffer[NTP_PACKET_SIZE];  
EthernetUDP Udp;                    
unsigned long ntpLastUpdate = 0;    
time_t prevDisplay = 0;

in the setup after getting the ip address...:

//Try to get the date and time
   int trys=0;
   while((!getTimeAndDate()) && trys<10) {
     Serial.println("get time failed");
     trys++;
   }

at the end of the setup:

int getTimeAndDate() {
   int flag=0;
   Udp.begin(localPort);
   sendNTPpacket(timeServer);
   delay(1000);
   if (Udp.parsePacket()){
     Udp.read(packetBuffer,NTP_PACKET_SIZE);  // read the packet into the buffer
     unsigned long highWord, lowWord, epoch;
     highWord = word(packetBuffer[40], packetBuffer[41]);
     lowWord = word(packetBuffer[42], packetBuffer[43]);  
     epoch = highWord << 16 | lowWord;
     epoch = epoch - 2208988800 + timeZoneOffset;
     flag=1;
     setTime(epoch);
     ntpLastUpdate = now();
   }
   return flag;
}
 
unsigned long sendNTPpacket(IPAddress& address)
{
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  packetBuffer[0] = 0b11100011;
  packetBuffer[1] = 0;
  packetBuffer[2] = 6;
  packetBuffer[3] = 0xEC;
  packetBuffer[12]  = 49;
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;                  
  Udp.beginPacket(address, 123);
  Udp.write(packetBuffer,NTP_PACKET_SIZE);
  Udp.endPacket();
}
 
// Clock display of the time and date (Basic)
void clockDisplay(){
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year());
  Serial.println();
}
 
// Utility function for clock display: prints preceding colon and leading 0
void printDigits(int digits){
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

Hope this helps! For me this is working fine since many many days... And thanks again for those who helped me!

how do i get the ip address for the time server from google? i am from malta (small country in europe) and can not find one for my country
also from the last part of code that you sent me, you changed nothing right?

i m still getting "get time failed"

You can use nslookup from a command prompt to get a valid NTP server.

nslookup pool.ntp.org

You can also use a dns request from your sketch to resolve the same domain name.

#include <SPI.h>
#include <Ethernet.h>
#include <Dns.h>

byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };

void setup() {
  Serial.begin(9600);

  pinMode(4,OUTPUT);
  digitalWrite(4,HIGH);

  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    for(;;)
      ;
  }
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());

  IPAddress ntpIP;

  DNSClient dns;
  dns.begin(Ethernet.dnsServerIP());
  if(dns.getHostByName("pool.ntp.org",ntpIP) == 1) {
    Serial.print("NTP IP from the pool: ");
    Serial.println(ntpIP);
  }
  else Serial.println("DNS lookup failed");
}

void loop() {
}

it workied perfectly :smiley: thankyou very much... it appears that my problem was the ipadress all the time :smiley: thanks once again

Hi Surferr tim.... Sorry for disturbing you once again.

I have managed to complete the full program and it worked perfectly at home. Then I moved my boards to another modem, changed my IPADDRESS according to ntslookup from command prompt but it did not connect. I connected the laptop to the modem (via cable) and there was internet. Do you know what I should do?

Stefan_28:
I have managed to complete the full program and it worked perfectly at home. Then I moved my boards to another modem, changed my IPADDRESS according to ntslookup from command prompt but it did not connect. I connected the laptop to the modem (via cable) and there was internet. Do you know what I should do?

I'm not sure. It could be any of the following:
The NTP server is down.
The router is not connection tracking UDP packets.
The UDP forward chain is blocked on that router.

How can i check for those error?
I tried every manner today but I did not manage to fix my problem. I noticed the next details though:
Usually 100M and FULLD LEDs on the ethernet shield just switch on and stay on... today it continued to blink
the RX never blinked... as if it never received but only transmitted... does it make any difference?

How can I check for those errors?
I tried in all possible ways today, but did not manage to solve anything.
If this could be of any help, I noticed the following details: usually 100M and FULLD LEDs on the ethernet shield just switch on and stay on. Today, they kept blinking non-stop. Also, the RX never blinked as if I received nothing but continued to transmit. Does this make a difference?