avaldebe / UxTClib

ctime clock library for ESP8266 and ESP32
MIT License
3 stars 1 forks source link

Use core time library for the ESP8266/ESP32 #4

Closed avaldebe closed 6 years ago

avaldebe commented 6 years ago

The core ESP8266/ESP32 time libraries gives a way to keep the internal clock synkec with a NTP server(s). This is configured once by calling configTime from setup, and subsequent calls to the NTP server(s) will be handled behind the scenes.

avaldebe commented 6 years ago

The following example prints the local hour of the day. It is a mash-up of this question and asnwer

#include <ESP8266WiFi.h>
#include <time.h>

const char* ssid = "";
const char* password = "";
int timezone = 3;
int dst = 0;

void setup() {
  Serial.begin(115200);
  Serial.setDebugOutput(true);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("\nConnecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }
  configTime(timezone * 3600, dst * 0, "pool.ntp.org", "time.nist.gov");
  Serial.println("\nWaiting for time");
  while (!time(nullptr)) {
    Serial.print(".");
    delay(1000);
  }
  Serial.println("");
}

void loop() {
  time_t now;
  struct tm * timeinfo;
  time(&now);
  timeinfo = localtime(&now);  
  Serial.println(timeinfo->tm_hour);
  delay(1000);
}
avaldebe commented 6 years ago

There are many different time.h. In addition to the in addition to the core/HAL library previously mentioned, the ESP8266/ESP32 c-library provides localtime, gmtime, time_t and struct tm. The Arduino implementation is different, but still provides time_t. In all of them time_t is implemented as unixtime.

HeinvdW commented 3 years ago

You can skip the while loop obtaining time by adding the time definition before the WiFi connect.

#include <ESP8266WiFi.h>
#include <time.h>

const char* ssid = "";
const char* password = "";
int timezone = 3;
int dst = 0;

void setup() {
  Serial.begin(115200);
  Serial.setDebugOutput(true);
  WiFi.mode(WIFI_STA);

  // Init and get the time works automagic
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); 
  setenv("TZ","CET-1CEST-2,M3.5.0,M10.5.0/3,1",1); //Europe Berlin

  WiFi.begin(ssid, password);
  Serial.println("\nConnecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }
}

void loop() {
  time_t now;
  struct tm * timeinfo;
  time(&now);
  timeinfo = localtime(&now);  
  Serial.println(timeinfo->tm_hour);
  delay(1000);
}