[GH-ISSUE #1097] Failing to get correct NTP time returned when using WiFiManager! #938

Closed
opened 2026-02-28 01:27:45 +03:00 by kerem · 1 comment
Owner

Originally created by @ZebNZ on GitHub (Jul 14, 2020).
Original GitHub issue: https://github.com/tzapu/WiFiManager/issues/1097

Hi all,

I am trying to get the current GMT time from an NTP server.

I connect to WiFi successfully using the WiFiManager Library, but I get this "date and time" returned:
Epoch Time: 14
Hour: 0
Minutes: 0
Seconds: 14
Week Day: 4
Month: 1
Year: 1970
Current date: 1970-01-04T00:00:14Z

Note that the numerals after the "T" increment (like a stopwatch)

Code (not working):

#include <FS.h>                   //this needs to be first, or it all crashes and burns :)
#include <WiFiUdp.h>
#include <NTPClient.h>
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>      //our library for managing credentials
#include <ArduinoJson.h>

/* DEFINE PARAMETERS FOR THE USER TO INPUT*/
char username[15]; //username
char password[20]; //password

const byte interruptPin = 0; //reset wifi credentials interrupt pin

bool shouldSaveConfig = false; //flag for saving data

bool inloop = false; //varaible to store if we are in the loop yet

/* CALLBACK TO NOTIFYING US OF THE NEED TO SAVE CONGIG */
void saveConfigCallback() {
  Serial.println("Should save config");
  shouldSaveConfig = true;
}

/* WIFIMANAGER */
WiFiManager wifiManager;

/* ADD AN INTERRUPT FOR RESETING ALL SAVED CREDENTIALS */
void ICACHE_RAM_ATTR Interrupt(); //attach an interrupt for reseting all credentials

/* DEFINE NTP CLIENT TO GET TIME */
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org");

/* SETUP */
void setup() {
  Serial.begin(115200);
  Serial.println();

  /* SETUP INTERRUPT PIN */
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), Interrupt, FALLING);

  /* READ CONFIGURATION FROM FS JSON */
  Serial.println("mounting FS...");
  if (SPIFFS.begin()) {
    Serial.println("mounted file system");
    if (SPIFFS.exists("/config.json")) {
      //file exists, reading and loading
      Serial.println("reading config file");
      File configFile = SPIFFS.open("/config.json", "r");
      if (configFile) {
        Serial.println("opened config file");
        size_t size = configFile.size();
        // Allocate a buffer to store contents of the file.
        std::unique_ptr<char[]> buf(new char[size]);

        configFile.readBytes(buf.get(), size);

        DynamicJsonDocument json(1024);
        auto deserializeError = deserializeJson(json, buf.get());
        serializeJson(json, Serial);
        /* IF YOU LOADED THE CONFIG FILE SUCCESSFULLY */
        if (!deserializeError) {
          Serial.println("\nparsed json");

          strcpy(username, json["username"]);
          strcpy(password, json["password"]);

          Serial.println("Username");
          Serial.println(username);
          Serial.println("Password");
          Serial.println(password);
        }
        /* IF YOU FAILED TO LOAD CONFIG FILE */
        else {
          Serial.println("failed to load json config");
        }
        configFile.close();
      }
    }
  }
  /* IF YOU FAILED TO LOAD FS JSON FILE */
  else {
    Serial.println("failed to mount FS");
  } //end read

  // The extra parameters to be configured (can be either global or just in the setup)
  // After connecting, parameter.getValue() will get you the configured value
  // id/name placeholder/prompt default length

  /* ADD PARAMETERS FOR USER INPUT */
  WiFiManagerParameter custom_username("username", "Username", username, 15); //input for Username
  WiFiManagerParameter custom_password("password", "Password", password, 20); //input for Password

  /* SET CONFIG SACE NOTIFY CALLBACK */
  wifiManager.setSaveConfigCallback(saveConfigCallback);

  /* SET STATIC IP */
  wifiManager.setSTAStaticIPConfig(IPAddress(10, 0, 1, 99), IPAddress(10, 0, 1, 1), IPAddress(255, 255, 255, 0));

  /* PARAMETERS */
  wifiManager.addParameter(&custom_username); //for Username
  wifiManager.addParameter(&custom_password); //for Password

  /* TRY TO CONNECT TO WIFI WITH SSID AND PASSWORD, IF IT DOES NOT CONNECT IT STARTS AN ACCESS POINT WITH THE SPECIFIED NAME
    AND GOES INTO A BLOCKING LOOP AWAITING CONFIGURATION */
  if (!wifiManager.autoConnect("Credentials", "password")) {
    Serial.println("failed to connect and hit timeout");
    delay(3000);
    //reset and try again, or maybe put it to deep sleep
    ESP.reset();
    delay(5000);
  }

  /* IF YOU GET HERE YOU HAVE CONNECTED TO WIFI */
  Serial.println("Connected!");

  /* READ THE UPDATED PARAMETERS */
  strcpy(username, custom_username.getValue()); //Username
  strcpy(password, custom_password.getValue()); //Password

  /* SAVE THE CUSTOM PARAMETERS TO THE FS JSON FILE */
  if (shouldSaveConfig) {
    Serial.println("saving config");

    DynamicJsonDocument json(1024);

    json["username"] = username; //username
    json["password"] = password; //password

    /* IF YOU CAN'T OPEN THE JSON CONFIGURATION FILE */
    File configFile = SPIFFS.open("/config.json", "w");
    if (!configFile) {
      Serial.println("failed to open config file for writing");
    }

    /* SERIAL PRINT WHAT THE JSON FILE CURRENTLY CONTAINS */
    serializeJson(json, Serial);
    serializeJson(json, configFile);

    configFile.close();
    //end save
  }
  Serial.println("local ip");
  Serial.println(WiFi.localIP()); //print it's IP address

  // Initialize a NTPClient to get time
  timeClient.begin();
  timeClient.setTimeOffset(0);
}

/* LOOP */
void loop() {
  timeClient.update();

  unsigned long epochTime = timeClient.getEpochTime();
  Serial.print("Epoch Time: ");
  Serial.println(epochTime);

  int currentHour = timeClient.getHours();
  Serial.print("Hour: ");
  Serial.println(currentHour);

  int currentMinute = timeClient.getMinutes();
  Serial.print("Minutes: ");
  Serial.println(currentMinute);

  int currentSecond = timeClient.getSeconds();
  Serial.print("Seconds: ");
  Serial.println(currentSecond);

  int currentDay = timeClient.getDay();
  Serial.print("Week Day: ");
  Serial.println(currentDay);

  //Get a time structure
  struct tm *ptm = gmtime ((time_t *)&epochTime);

  int currentMonth = ptm->tm_mon + 1;
  Serial.print("Month: ");
  Serial.println(currentMonth);

  int currentYear = ptm->tm_year + 1900;
  Serial.print("Year: ");
  Serial.println(currentYear);

  //Print complete date:
  String receivedTimeDate = (String(currentYear) + "-" + toStringAddZero(currentMonth) + "-" + toStringAddZero(currentDay)) + ("T") + (toStringAddZero(currentHour) + ":" + toStringAddZero(currentMinute) + ":" + toStringAddZero(currentSecond)) + ("Z");
  Serial.print("Current date: ");
  Serial.println(receivedTimeDate);

  Serial.println("");

  delay(2000);
}

String toStringAddZero(int data)
{
  String st = "";
  if (data < 10)
  {
    st = "0" + String(data);
  }
  else
  {
    st = String(data);
  }
  return st;
}

/* INTERRUPT */
void Interrupt() {
  if (inloop == true) { //when the board first boots up unfortuantly it runs the interrupt and resets all our credentials, so we need to ensure that we are in the loop before the option to reset the credentials comes available
    Serial.println("Resetting");
    wifiManager.resetSettings(); //reset all saved credentials
    ESP.reset(); //restart the ESP
  }
}

But this code which connects to the WiFi network without using the WiFiMananger works fine!

Code (working):

#include <ESP8266WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>

// Replace with your network credentials
const char *ssid     = "****";
const char *password = "*****";

// Define NTP Client to get time
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org");

void setup() {
  // Initialize Serial Monitor
  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(".");
  }

// Initialize a NTPClient to get time
  timeClient.begin();
  timeClient.setTimeOffset(0);
}

void loop() {
    timeClient.update();

  unsigned long epochTime = timeClient.getEpochTime();
  Serial.print("Epoch Time: ");
  Serial.println(epochTime);

  int currentHour = timeClient.getHours();
  Serial.print("Hour: ");
  Serial.println(currentHour);

  int currentMinute = timeClient.getMinutes();
  Serial.print("Minutes: ");
  Serial.println(currentMinute);

  int currentSecond = timeClient.getSeconds();
  Serial.print("Seconds: ");
  Serial.println(currentSecond);

  int currentDay = timeClient.getDay();
  Serial.print("Week Day: ");
  Serial.println(currentDay);

  //Get a time structure
  struct tm *ptm = gmtime ((time_t *)&epochTime);

  int currentMonth = ptm->tm_mon + 1;
  Serial.print("Month: ");
  Serial.println(currentMonth);

  int currentYear = ptm->tm_year + 1900;
  Serial.print("Year: ");
  Serial.println(currentYear);

  //Print complete date:
  String receivedTimeDate = (String(currentYear) + "-" + toStringAddZero(currentMonth) + "-" + toStringAddZero(currentDay)) + ("T") + (toStringAddZero(currentHour) + ":" + toStringAddZero(currentMinute) + ":" + toStringAddZero(currentSecond)) + ("Z");
  Serial.print("Current date: ");
  Serial.println(receivedTimeDate);

  Serial.println("");

  delay(2000);
}

String toStringAddZero(int data)
{
  String st = "";
  if (data < 10)
  {
    st = "0" + String(data);
  }
  else
  {
    st = String(data);
  }
  return st;
}

I guess that this means there is a problem with it connecting to WiFi using the WiFiManager library, even though it says it has connected successfully?

Does anyone know what possibly might be wrong?

Any help would be greatly appreciated!

Thanks,

Zeb

Originally created by @ZebNZ on GitHub (Jul 14, 2020). Original GitHub issue: https://github.com/tzapu/WiFiManager/issues/1097 Hi all, I am trying to get the current GMT time from an NTP server. I **connect to WiFi successfully** using the WiFiManager Library, but I get this "date and time" returned: Epoch Time: 14 Hour: 0 Minutes: 0 Seconds: 14 Week Day: 4 Month: 1 Year: 1970 Current date: 1970-01-04T00:00:14Z Note that the numerals after the "T" increment (like a stopwatch) Code (not working): ``` #include <FS.h> //this needs to be first, or it all crashes and burns :) #include <WiFiUdp.h> #include <NTPClient.h> #include <ESP8266WiFi.h> #include <DNSServer.h> #include <ESP8266WebServer.h> #include <WiFiManager.h> //our library for managing credentials #include <ArduinoJson.h> /* DEFINE PARAMETERS FOR THE USER TO INPUT*/ char username[15]; //username char password[20]; //password const byte interruptPin = 0; //reset wifi credentials interrupt pin bool shouldSaveConfig = false; //flag for saving data bool inloop = false; //varaible to store if we are in the loop yet /* CALLBACK TO NOTIFYING US OF THE NEED TO SAVE CONGIG */ void saveConfigCallback() { Serial.println("Should save config"); shouldSaveConfig = true; } /* WIFIMANAGER */ WiFiManager wifiManager; /* ADD AN INTERRUPT FOR RESETING ALL SAVED CREDENTIALS */ void ICACHE_RAM_ATTR Interrupt(); //attach an interrupt for reseting all credentials /* DEFINE NTP CLIENT TO GET TIME */ WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, "pool.ntp.org"); /* SETUP */ void setup() { Serial.begin(115200); Serial.println(); /* SETUP INTERRUPT PIN */ pinMode(interruptPin, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(interruptPin), Interrupt, FALLING); /* READ CONFIGURATION FROM FS JSON */ Serial.println("mounting FS..."); if (SPIFFS.begin()) { Serial.println("mounted file system"); if (SPIFFS.exists("/config.json")) { //file exists, reading and loading Serial.println("reading config file"); File configFile = SPIFFS.open("/config.json", "r"); if (configFile) { Serial.println("opened config file"); size_t size = configFile.size(); // Allocate a buffer to store contents of the file. std::unique_ptr<char[]> buf(new char[size]); configFile.readBytes(buf.get(), size); DynamicJsonDocument json(1024); auto deserializeError = deserializeJson(json, buf.get()); serializeJson(json, Serial); /* IF YOU LOADED THE CONFIG FILE SUCCESSFULLY */ if (!deserializeError) { Serial.println("\nparsed json"); strcpy(username, json["username"]); strcpy(password, json["password"]); Serial.println("Username"); Serial.println(username); Serial.println("Password"); Serial.println(password); } /* IF YOU FAILED TO LOAD CONFIG FILE */ else { Serial.println("failed to load json config"); } configFile.close(); } } } /* IF YOU FAILED TO LOAD FS JSON FILE */ else { Serial.println("failed to mount FS"); } //end read // The extra parameters to be configured (can be either global or just in the setup) // After connecting, parameter.getValue() will get you the configured value // id/name placeholder/prompt default length /* ADD PARAMETERS FOR USER INPUT */ WiFiManagerParameter custom_username("username", "Username", username, 15); //input for Username WiFiManagerParameter custom_password("password", "Password", password, 20); //input for Password /* SET CONFIG SACE NOTIFY CALLBACK */ wifiManager.setSaveConfigCallback(saveConfigCallback); /* SET STATIC IP */ wifiManager.setSTAStaticIPConfig(IPAddress(10, 0, 1, 99), IPAddress(10, 0, 1, 1), IPAddress(255, 255, 255, 0)); /* PARAMETERS */ wifiManager.addParameter(&custom_username); //for Username wifiManager.addParameter(&custom_password); //for Password /* TRY TO CONNECT TO WIFI WITH SSID AND PASSWORD, IF IT DOES NOT CONNECT IT STARTS AN ACCESS POINT WITH THE SPECIFIED NAME AND GOES INTO A BLOCKING LOOP AWAITING CONFIGURATION */ if (!wifiManager.autoConnect("Credentials", "password")) { Serial.println("failed to connect and hit timeout"); delay(3000); //reset and try again, or maybe put it to deep sleep ESP.reset(); delay(5000); } /* IF YOU GET HERE YOU HAVE CONNECTED TO WIFI */ Serial.println("Connected!"); /* READ THE UPDATED PARAMETERS */ strcpy(username, custom_username.getValue()); //Username strcpy(password, custom_password.getValue()); //Password /* SAVE THE CUSTOM PARAMETERS TO THE FS JSON FILE */ if (shouldSaveConfig) { Serial.println("saving config"); DynamicJsonDocument json(1024); json["username"] = username; //username json["password"] = password; //password /* IF YOU CAN'T OPEN THE JSON CONFIGURATION FILE */ File configFile = SPIFFS.open("/config.json", "w"); if (!configFile) { Serial.println("failed to open config file for writing"); } /* SERIAL PRINT WHAT THE JSON FILE CURRENTLY CONTAINS */ serializeJson(json, Serial); serializeJson(json, configFile); configFile.close(); //end save } Serial.println("local ip"); Serial.println(WiFi.localIP()); //print it's IP address // Initialize a NTPClient to get time timeClient.begin(); timeClient.setTimeOffset(0); } /* LOOP */ void loop() { timeClient.update(); unsigned long epochTime = timeClient.getEpochTime(); Serial.print("Epoch Time: "); Serial.println(epochTime); int currentHour = timeClient.getHours(); Serial.print("Hour: "); Serial.println(currentHour); int currentMinute = timeClient.getMinutes(); Serial.print("Minutes: "); Serial.println(currentMinute); int currentSecond = timeClient.getSeconds(); Serial.print("Seconds: "); Serial.println(currentSecond); int currentDay = timeClient.getDay(); Serial.print("Week Day: "); Serial.println(currentDay); //Get a time structure struct tm *ptm = gmtime ((time_t *)&epochTime); int currentMonth = ptm->tm_mon + 1; Serial.print("Month: "); Serial.println(currentMonth); int currentYear = ptm->tm_year + 1900; Serial.print("Year: "); Serial.println(currentYear); //Print complete date: String receivedTimeDate = (String(currentYear) + "-" + toStringAddZero(currentMonth) + "-" + toStringAddZero(currentDay)) + ("T") + (toStringAddZero(currentHour) + ":" + toStringAddZero(currentMinute) + ":" + toStringAddZero(currentSecond)) + ("Z"); Serial.print("Current date: "); Serial.println(receivedTimeDate); Serial.println(""); delay(2000); } String toStringAddZero(int data) { String st = ""; if (data < 10) { st = "0" + String(data); } else { st = String(data); } return st; } /* INTERRUPT */ void Interrupt() { if (inloop == true) { //when the board first boots up unfortuantly it runs the interrupt and resets all our credentials, so we need to ensure that we are in the loop before the option to reset the credentials comes available Serial.println("Resetting"); wifiManager.resetSettings(); //reset all saved credentials ESP.reset(); //restart the ESP } } ``` **But** this code which connects to the WiFi network without using the WiFiMananger works fine! Code (working): ``` #include <ESP8266WiFi.h> #include <NTPClient.h> #include <WiFiUdp.h> // Replace with your network credentials const char *ssid = "****"; const char *password = "*****"; // Define NTP Client to get time WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, "pool.ntp.org"); void setup() { // Initialize Serial Monitor 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("."); } // Initialize a NTPClient to get time timeClient.begin(); timeClient.setTimeOffset(0); } void loop() { timeClient.update(); unsigned long epochTime = timeClient.getEpochTime(); Serial.print("Epoch Time: "); Serial.println(epochTime); int currentHour = timeClient.getHours(); Serial.print("Hour: "); Serial.println(currentHour); int currentMinute = timeClient.getMinutes(); Serial.print("Minutes: "); Serial.println(currentMinute); int currentSecond = timeClient.getSeconds(); Serial.print("Seconds: "); Serial.println(currentSecond); int currentDay = timeClient.getDay(); Serial.print("Week Day: "); Serial.println(currentDay); //Get a time structure struct tm *ptm = gmtime ((time_t *)&epochTime); int currentMonth = ptm->tm_mon + 1; Serial.print("Month: "); Serial.println(currentMonth); int currentYear = ptm->tm_year + 1900; Serial.print("Year: "); Serial.println(currentYear); //Print complete date: String receivedTimeDate = (String(currentYear) + "-" + toStringAddZero(currentMonth) + "-" + toStringAddZero(currentDay)) + ("T") + (toStringAddZero(currentHour) + ":" + toStringAddZero(currentMinute) + ":" + toStringAddZero(currentSecond)) + ("Z"); Serial.print("Current date: "); Serial.println(receivedTimeDate); Serial.println(""); delay(2000); } String toStringAddZero(int data) { String st = ""; if (data < 10) { st = "0" + String(data); } else { st = String(data); } return st; } ``` I guess that this means there is a problem with it connecting to WiFi using the WiFiManager library, even though it says it has connected successfully? Does anyone know what possibly might be wrong? Any help would be greatly appreciated! Thanks, Zeb
kerem closed this issue 2026-02-28 01:27:45 +03:00
Author
Owner

@ZebNZ commented on GitHub (Jul 14, 2020):

Just needed to get rid of the "Static IP" :)

<!-- gh-comment-id:658014570 --> @ZebNZ commented on GitHub (Jul 14, 2020): Just needed to get rid of the "Static IP" :)
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
starred/WiFiManager#938
No description provided.