NTP Server not Returning Correct Time

Hi all,

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

I connect to WiFi successfully using the WiFiManager Library GitHub - tzapu/WiFiManager: ESP8266 WiFi Connection manager with web captive portal

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:

#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
  }
}

Does anyone know what might be wrong?

Thanks very much,

Zeb

....By the way I am using an ESP8266

I have tried this code here and it works fine:

#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

The comments do not seem in line with the use of “if”...

 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!");

I would say it should be using “while” if you want the comments and output of “Connected!” to be correct.

Edit: Even assuming ESP.reset() maybe restarts the sketch, we still have...

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

Do those static IPs match the configuration of the WiFi network you are connecting to?
If not then you’ll be able to connect but not be able to route any traffic.

What IP address is printed by...

 Serial.println("local ip");
  Serial.println(WiFi.localIP()); //print it's IP address

Meanwhile I expect your second example is probably using DHCP to get correct IP addresses from your WiFi access point.

Many thanks pcbbc, it works!

Thanks again,

Zeb

Getting NTP time from the same server every 2 seconds counts as abuse on some servers, you will eventually get a "kiss of death" message, if you ignore it, you will be locked out and your requests will be ignored.