c++arduinoesp8266ntpplatformio

Unable to get time form the NTP server in esp8266, arduino


I know I am successfully connected to the network as it's visible in my phone's hotspot. However I am unable to get the time using <Time.h> library through NTP server.

Thanks in advance. I will really appreciate your suggestions.

platformio.int

board_build.f_cpu = 160000000L
platform = espressif8266
board = nodemcuv2
framework = arduino
lib_deps = 
    paulstoffregen/Time@^1.6

Arduino code

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <Time.h>
#include "WifiCtrl.h"   // Wifi setup
WifiCtrl WifiControl;


void setup()
{
    // Starting serial monitor service
    // ----------------------------------------------
    Serial.begin(9600);

    // This address the function which is for wifi setup
    WifiControl.setWifi();


    // Load time from the NTP server...
    time_t now;
    // Serial.println("Setting time using SNTP");
    configTime(5 * 3600, 1800, "pool.ntp.org", "time.nist.gov");
    now = time(nullptr);

    struct tm timeinfo;
    gmtime_r(&now, &timeinfo);
    Serial.print("Current time: ");
    Serial.print(asctime(&timeinfo));
}

void loop() {}

Solution

  • You must wait sometime before printing the time data.

    Hope this work for you

    #include <Arduino.h>
    #include <ESP8266WiFi.h>
    #include <Time.h>
    
    void setup()
    {
        // Starting serial monitor service
        // ----------------------------------------------
        Serial.begin(9600);
    
        // Load time from the NTP server...
        time_t now;
        // Serial.println("Setting time using SNTP");
        configTime(5 * 3600, 1800, "pool.ntp.org", "time.nist.gov");
        now = time(nullptr);
    
        // create some delay before printing
        while (now < 1510592825)
        {
            delay(500);
            Serial.print(".");
            time(&now);
        }
    
        struct tm *timeCur;
        timeCur = localtime(&now);
    
        // Printing time..
        Serial.println(timeCur->tm_hour);
        Serial.println(timeCur->tm_min);
        Serial.println(timeCur->tm_sec);
    }
    
    void loop() {}