#include <WiFi.h>
#include <WiFiUdp.h>
#include <Ticker.h>
#define NTP_SRV "pool.ntp.org"
#define NTP_DELAY 10 //milliseconds
#define NTP_TIMEOUT 10 // seconds
Ticker tkNtp;
const timeval ntpDate() {
timeval ntpTime = {0};
WiFiUDP udp;
uint8_t sendPacket[48] = {0};
sendPacket[0] = 0x1B;
udp.begin(123);
udp.beginPacket(NTP_SRV, 123);
udp.write(sendPacket, 48);
uint64_t req_start = micros();
udp.endPacket();
uint32_t ntpLoops = NTP_TIMEOUT * 1000UL / NTP_DELAY;
for (int z=0; z < ntpLoops; z++) {
delay(NTP_DELAY);
if (udp.parsePacket()) {
uint64_t travel = (micros() - req_start) / 2;
byte recvPacket[48];
if (udp.read(recvPacket, 48) == 48) {
udp.stop();
int64_t sec = 0;
uint64_t moments = 0;
for (int x=0; x<4; x++)
sec += (uint32_t)recvPacket[40+x] << ((3-x)*8); //get the secs
sec -= 2208988800; // 70 years (1900-1970)
for (int x=0; x<3; x++)
moments += (uint32_t)recvPacket[40+4+x] << ((2-x)*8); // get the moments
moments = moments * 1E6 / 0xFFFFFF; // convert moments to microseconds
if (travel > moments) {
sec--;
moments += 1E6;
}
moments -= travel;
ntpTime = {sec, (int32_t)moments};
settimeofday((const timeval*)&ntpTime, NULL);
break;
}
}
}
return ntpTime;
}
void setup() {
Serial.begin(115200);
Serial.println("Hello, ESP32!");
WiFi.begin("Wokwi-GUEST","");
WiFi.waitForConnectResult();
ntpDate();
tkNtp.attach(3600, ntpDate);
}
void loop() {
Serial.println(time(NULL));
delay(10000);
}
Loading
esp32-devkit-c-v4
esp32-devkit-c-v4