3

I want to synchronize time with NTP server once in some time. I am using DOIT ESP32 DEVKIT V1, I tried with getLocalTime() function but it returned true even without wifi, but as I know without wifi it can not conect to NTP server. Can anyone say if it is possible how to correctly synchronize time with NTP server? Maybe with some other libraries or with other functions.

 #include <WiFi.h>
 #include "time.h"
 const int gmtOffset_sec = 7200;
 const int daylightOffset_sec = 3600;
 const char* ntpServer = "pool.ntp.org";
 void setup() {
 Serial.begin(115200);
 Serial.println("Board started\n");
 WiFi.begin("<ssid>", "<password>");
 struct tm timeinfo;
 
 Serial.print("Connecting...");
 while (WiFi.status() != WL_CONNECTED) {
 delay(500);
 Serial.print(".");
 }
 Serial.println("");
 Serial.println("WiFi connected.");
 configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
 if (!getLocalTime(&timeinfo)) {
 Serial.println("Failed to obtain time 1");
 } else {
 Serial.println("Time obtained 1");
 }
 WiFi.disconnect(true);
 WiFi.mode(WIFI_OFF);
 if (!getLocalTime(&timeinfo)) {
 Serial.println("Failed to obtain time 2");
 } else {
 Serial.println("Time obtained 2");
 }
 }
 void loop() {
 }

The output to console is:

Board started
Connecting....
WiFi connected.
Time obtained 1
Time obtained 2

But I would expect 2nd output to be Failed to obtain time 2.

asked Sep 23, 2022 at 15:21
7
  • 1
    Also, why the code I posted does not have syntax highlighted? Commented Sep 23, 2022 at 15:28
  • 2
    You can get syntax highlighting with a line ```c++ before the code, and ``` after it. Commented Sep 23, 2022 at 15:52
  • upvote for asking how to present readable code Commented Sep 23, 2022 at 16:51
  • what is the question? it can take some seconds until time is retrieved after connected to WiFi and Internet. getLocalTime returns time from internal RTC which is set with time retrieved from NTC server Commented Sep 23, 2022 at 16:56
  • 2
    getLocalTime has nothing to do with NTP. It gets time from RTC. the SDK retrieves time from the Internet and sets it to RTC periodically. study this example github.com/esp8266/Arduino/blob/master/libraries/esp8266/… Commented Sep 26, 2022 at 19:30

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.