fbiego / ESP32Time

An Arduino library for setting and retrieving internal RTC time on ESP32 boards
MIT License
212 stars 36 forks source link

Lost 2 hours after 1 read #7

Closed ebelouet closed 1 year ago

ebelouet commented 3 years ago

HI, Frist hour is ok and after is bad with 2 minus hours, where is mistake ?

include

include

include <sys/time.h>

include

define uS_TO_S_FACTOR 1000000

const char ssid = ""; const char password = "";

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

struct tm getTimeStruct() { struct tm timeinfo; // there is a default 5000 ms timeout when the year // is not in the 1900..2016 range. getLocalTime(&timeinfo, 0); return timeinfo; } struct tm timeinfo = getTimeStruct();

void setup() { //struct tm timeinfo = getTimeStruct(); // put your setup code here, to run once: Serial.begin(115200); Serial.printf("Bootcount = %d\n", bootCount); if (!bootCount) { //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"); Serial.println("Getting Time."); configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);

if(!getLocalTime(&timeinfo)){ Serial.println("Failed to obtain time"); return; } //printLocalTime();

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

//struct tm timeinfo = getTimeStruct();

// timeinfo.tm_hour = 22; //timeinfo.tm_min = 02; // timeinfo.tm_sec = 00; //timeinfo.tm_mon = 2; // January //timeinfo.tm_mday = 31; // 1st //timeinfo.tm_year = 2021 - 1900; // 2021

struct timeval tv;
tv.tv_sec = mktime(&timeinfo);
settimeofday(&tv, NULL);

} ++bootCount; }

void loop() { // put your main code here, to run repeatedly: int now = millis(); //struct tm timeinfo = getTimeStruct(); now = millis() - now; Serial.printf("%d:%02d:%02d (%d msecs)\n", timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec, now);

Serial.printf("%d:%02d:%02d\n ", timeinfo.tm_mday,timeinfo.tm_mon, timeinfo.tm_year+1900);

esp_sleep_enable_timer_wakeup(60 * uS_TO_S_FACTOR);

Serial.println("Going to sleep now"); delay(1000); Serial.flush(); esp_deep_sleep_start(); }

gaetan-hexadog commented 3 years ago

same here... it seems after deep sleep we lost gmtOffset_sec and daylightOffset_sec we have to reconfigure it after wake up.

void setup() {
  // ...
  if(esp_sleep_get_wakeup_cause() == ESP_SLEEP_WAKEUP_TIMER)
  {
     configTime(gmtOffset_sec, daylightOffset_sec, NULL);
  }
  // ...
}