Reputation: 68
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() {}
Upvotes: 4
Views: 2053
Reputation: 13
Try this as well for date and time
#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");
//for india UTC+5:30 so 5*3600(5 hours in seconds) and 0.5*3600=1800(half hour in seconds)
now = time(nullptr);
// create some delay before printing
while (now < 1510592825)
{
delay(500);
Serial.print(".");
time(&now);
}
//experimental code //may be its not the best way, but it works well.
struct tm* L_tm = localtime(&now);
Serial.print("Local time: ");
Serial.print(L_tm->tm_mday);
Serial.print("/");
Serial.print(L_tm->tm_mon + 1);
Serial.print("/");
Serial.print(L_tm->tm_year + 1900);
Serial.print(" ");
Serial.print(L_tm->tm_hour);
Serial.print(":");
Serial.print(L_tm->tm_min);
Serial.print(":");
Serial.println(L_tm->tm_sec);
//experimental code END
}
void loop() {}
Upvotes: 0
Reputation: 501
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() {}
Upvotes: 3