Hi,
I am using a ESP32 module and am coding in Arduino IDE. I was able to get the current date and time by polling NTP servers and using struct tm and getLocalTime() function. However, the time I receive back from the NTP server doing so is in seconds and I would like to have the time in milliseconds or microseconds precision.
After searching on the internet how I could do this, I found people recommend using struct timeval and function gettimeofday() instead. So I modified my code and tried it out.
But the output I get is something like: TimeVal-sec = 5 TimeVal-usec = 792802
It should return the number of seconds since January 1st 1970, which I don't get...
I'll post my code below. Hopefully someone can help me with this!
PS: I'm on Windows
void setup()
{
Serial.begin(9600);
//connect to WiFi
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
Serial.println(" CONNECTED");
//initialize NTP client and get the time
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer1, ntpServer2, ntpServer3);
//printLocalTime();
//disconnect WiFi as it's no longer needed
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
}
void printLocalTime()
{
struct timeval tv;
if (gettimeofday(&tv, NULL)!= 0) {
Serial.println("Failed to obtain time");
return;
}
Serial.print("TimeVal-sec = ");
Serial.print(tv.tv_sec);
Serial.print(" ");
Serial.print("TimeVal-usec = ");
Serial.print(tv.tv_usec);
Serial.println();
}