1

When using ESP8266 - getting seconds from epoch is done using

NTP.begin(NTPserver, 2, true);
delay(delay_tries);
time_t t = now();

while t stores amount of seconds from 1-1-1970.

When trying to do the same, using ESP32 - I cant get that numeric representation.

code below is from ESP32 example- updating time using NTP server ( process is done correct ). BUT when using now() yields 1970, as if NTP update has never occured.

How can I get time from Epoch ?

#include <WiFi.h>
#include "time.h"
#include <TimeLib.h>    <------- Added to original Code

const char* ssid       = "YOUR_SSID";
const char* password   = "YOUR_PASS";

const char* ntpServer = "pool.ntp.org";
const long  gmtOffset_sec = 3600;
const int   daylightOffset_sec = 3600;

void printLocalTime()
{
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("Failed to obtain time");
    return;
  }
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
}

void setup()
{
  Serial.begin(115200);

  //connect to WiFi
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
  }
  Serial.println(" CONNECTED");

  //init and get the time
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
  printLocalTime();

  //disconnect WiFi as it's no longer needed
  WiFi.disconnect(true);
  WiFi.mode(WIFI_OFF);
}

void loop()
{
  delay(1000);
  printLocalTime();
  Serial.println(now());   <-------- Added to original code
}
guyd
  • 1,049
  • 2
  • 26
  • 61

1 Answers1

2

to return 'epoch' seconds there is a function time in time.h

time_t now;
time(&now);

time_t is defined as long

this time is retrieved by the ESP32 SDK from NTP servers configured with ESP32 Arduino function configTime

EDIT: it is the standard C time() function

Juraj
  • 18,264
  • 4
  • 31
  • 49