With an ESP32, I’m writing a program to read the status of several sensors, about every 15 minutes with a timestamp. The strategy is to:
- connect to the local wifi
- get utc timestamp via NTP
- read sensor data
- disconnect from local wifi
- sleeping or doing other stuff for about 15 minutes, then connect to wifi again...
When searching the internet on how to use NTP to get timestamps, the same example code appears on several sites, e.g. ESP32 NTP Client-Server: Get Date and Time (Arduino IDE) | Random Nerd Tutorials
/*
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp32-date-time-ntp-client-server-arduino/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*/
#include <WiFi.h>
#include "time.h"
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
const char* ntpServer = "pool.ntp.org";
const long gmtOffset_sec = 0;
const int daylightOffset_sec = 3600;
void setup(){
Serial.begin(115200);
// Connect to Wi-Fi
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected.");
// Init and get the time
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
printLocalTime();
//disconnect WiFi as it's no longer needed
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
}
void loop(){
delay(1000);
printLocalTime();
}
void printLocalTime(){
struct tm timeinfo;
if(!getLocalTime(&timeinfo)){
Serial.println("Failed to obtain time");
return;
}
Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
// cropped other output
}
What I don’t understand in this example is that at the end of the setup part, the wifi connection is terminated. Even more, after WiFi.mode(WIFI_OFF)
, it seems like the ESP32 has no longer WiFi functionality (WiFi status: 255 == WL_NO_SHEILD
), why? None of the websites explaining this example go in to detail about this part of the code :-/
How can a call to getLocalTime
(while executing function printLocalTime
) in the eternal loop part get the current time if no connection to an NTP-server is present? Is the RTC functionality of the ESP32 used somehow, and if so how is it resynchronised after a while? Apparently getLocalTime
is to be called a single time with a wifi connection, and from there on it can do without...
Form within Adruino.cc I tried to get a clue going to the definition of getLocalTime
, which lead me to localTime_r
, which was a dead end…
Can anyone give me some clues?
Thank you.