2

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.

hungryman
  • 29
  • 3
  • 1
    Also, why the code I posted does not have syntax highlighted? – hungryman Sep 23 '22 at 15:28
  • 2
    You can get syntax highlighting with a line `\`\`\`c++` before the code, and `\`\`\`` after it. – Edgar Bonet Sep 23 '22 at 15:52
  • upvote for asking how to present readable code – jsotola Sep 23 '22 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 – Juraj Sep 23 '22 at 16:56
  • This link may help: https://linuxconfig.org/stay-time-synchronized-with-internet-time-server – Gil Sep 24 '22 at 23:45
  • @Juraj I want to update rtc time with NTP server time periodically. How to do it the first time - is known, just call ```getLocalTime()``` after setting parameters with ```configTime()```. But how to do it the 2nd, 3rd, ... time? ```getLocalTime()``` will return the local time and will not sync it with NTP server, am I right? – hungryman Sep 26 '22 at 19:21
  • 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 https://github.com/esp8266/Arduino/blob/master/libraries/esp8266/examples/NTP-TZ-DST/NTP-TZ-DST.ino – Juraj Sep 26 '22 at 19:30

0 Answers0