#include <WiFi.h>
#include <WiFiUdp.h>
#include <Ticker.h>
#define NTP_SRV "pool.ntp.org"
#define NTP_DELAY 100
#define NTP_TIMEOUT 20
Ticker tkNtp;
timeval ntp2tv(uint8_t* packet, uint8_t tvloc) {
int64_t sec = 0;
uint64_t moments = 0;
for (int x=0; x<4; x++)
sec += (uint32_t)packet[tvloc+x] << ((3-x)*8); //get the secs
sec -= 2208988800; // 70 years (1900-1970)
for (int x=0; x<3; x++)
moments += (uint32_t)packet[tvloc+4+x] << ((2-x)*8); // get the fraction
moments = moments * 1E6 / 0xFFFFFF; // convert moments to microseconds
return (timeval){sec, (int32_t)moments};
}
void ntpDate() {
WiFiUDP udp;
uint8_t sendPacket[48] = {0};
sendPacket[0] = 0x1B;
udp.begin(123);
udp.beginPacket(NTP_SRV, 123);
udp.write(sendPacket, 48);
udp.endPacket();
uint32_t ntpLoops = NTP_TIMEOUT * 1000 / NTP_DELAY;
for (int z=0; z < ntpLoops; z++) {
delay(NTP_DELAY);
if (udp.parsePacket()) {
byte recvPacket[48];
if (udp.read(recvPacket, 48) == 48) {
udp.stop();
timeval ntpTime = ntp2tv(recvPacket, 40);
settimeofday((const timeval*)&ntpTime, NULL);
Serial.printf("Time set: %lld\tms: %ld\n", ntpTime.tv_sec, ntpTime.tv_usec);
break;
}
}
}
}
void setup() {
Serial.begin(115200);
Serial.println("Hello, ESP32!");
WiFi.begin("Wokwi-GUEST","");
WiFi.waitForConnectResult();
ntpDate();
tkNtp.attach(3600, ntpDate);
}
void loop() {
delay(-1);
}