I have a esp8266 project which i target users to choose ethernet and if no cable connected it will use wifi.
now testing with lwip (enc28j60 module) with core 3.0.2. i noticed that if connected with ethernet method syncing with ntp server has strange behaviour.
This happens to internal or other external libraries.
It does not happen when connected with wifi .....
Let's say the i update (sync) with ntp server with a interval of 30 minutes. Sometimes the clock will be 30 minutes behind.
It's like the cache or udp buffer is not cleared of flushed. Setting the array to zeros did not help.
even with a small raw udp function i cannot pinpoint the problem.
In wifi modus it works fine.
uint32_t ntpSync()
{
//get a random server from the pool
//////////////////////////WiFi.hostByName(ntpServerName, timeServerIP);
dns_gethostbyname(ntpServerName, timeServerIP, NULL, NULL);
sendNTPpacket(timeServerIP); // send an NTP packet to a time server
// wait to see if a reply is available
delay(1000);
int cb = udp.parsePacket();
if (cb) {
//for(int i=0;i<NTP_PACKET_SIZE;i++) packetBuffer[i] = 0;
//memset(packetBuffer, 0, NTP_PACKET_SIZE);
// We've received a packet, read the data from it
udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
udp.flush();
//the timestamp starts at byte 40 of the received packet and is four bytes,
// or two words, long. First, esxtract the two words:
// combine the four bytes (two words) into a uint32_t integer
// this is NTP time (seconds since Jan 1 1900):
uint32_t secsSince1900 = packetBuffer[40] << 24 | packetBuffer[41] << 16 | packetBuffer[42] << 8 | packetBuffer[43];
// now convert NTP time into everyday time:
// Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
// subtract seventy years:
uint32_t epoch = secsSince1900 - 2208988800;
return epoch;
} else {
return false;
}
}
// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress& address)
{
//Serial.println("sending NTP packet...");
// 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();
}
the ////////// is for testing now only.
Why is it that with ethernet (#include <ENC28J60lwIP.h>) , sometimes ntp gives me a time earlier equal to the last update and with wifi (#include <ESP8266WiFi.h>) there is no problem?