Hi
I’d like to use an ESP32 to display time as HH:MM (no seconds) as accurately as possible. But I want to save battery, so the idea is
- use NTP server to set the time (once at the beginning, then as less as possible)
- display the time on an e-paper display
- go to deep sleep for (roughly) one minute
- go back to step 2 unless a given interval passed (say one or two hours, the longer the better) and go to step 1 (this is to recover accuracy as the RTC of the ESP32 drifts)
I don’t know if it’s the best way to do it. I’m open to any suggestion.
But my concern is more on the proper use of the Time library functions. Here is what I do:
Step 1:
/*
Connects to ntp server and set the time in the RTC of the ESP32
*/
void SetTimeByWifi () {
const char* ntpServer = "fr.pool.ntp.org";
//init and get the time
const long gmtOffset_sec = 0;
const int daylightOffset_sec = 0;
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
}
with
// Internet
#include <WiFi.h>
#include <HTTPClient.h>
Step 2: read the time
/*
Update timeinfo
*/
void WhatTime () {
time_t rawtime;
time (&rawtime);
rawtime += GMT * 3600; // GMT is set to 1 for me
timeinfo = localtime (&rawtime);
}
Step 2: use the time for display
currentTime[0] = (timeinfo->tm_hour + timeinfo->tm_isdst) % 24 / 10 + '0';
currentTime[1] = (timeinfo->tm_hour + timeinfo->tm_isdst) % 24 % 10 + '0';
currentTime[3] = timeinfo->tm_min / 10 + '0';
currentTime[4] = timeinfo->tm_min % 10 + '0';
Step 3: set the time to sleep
uint64_t sleepPeriod1 = 60100000ull; // 60 seconds sleep (plus an attempt to counter drift)
sleep_time = sleepPeriod1 - micros();
Step 4: after wakeup, the seconds should be zero, so I force them to 0
/*
Resets seconds to zero if wake up by timer
*/
void updateTime () {
getLocalTime(timeinfo);
if (timeinfo->tm_sec < 41) timeinfo->tm_sec = 0;
if (timeinfo->tm_sec > 40) timeinfo->tm_sec = 60;
time_t t = mktime(timeinfo);
struct timeval now0 = { .tv_sec = t };
settimeofday(&now0, NULL);
getLocalTime(timeinfo);
Serial.printf ("Update time : %s\n", asctime(timeinfo));
}
It begins to look like a gas factory (French expression ) so I’d like to know if there is any more accurate way to keep and update the time?
I don’t know much about ftp or udp: I’ve seen on the forum that udp was quicker. Shoud I use udp?