Timekeeping
The clock maintains accurate time using two sources: the DS3231 RTC (always available) and NTP over WiFi (updates when connected).
Boot Sequence
After the first NTP sync, the RTC holds accurate time. Subsequent boots read from the RTC immediately; WiFi sync is a "make it more accurate" bonus, not required.
Implementation
// In app_main() or a startup task:
// 1. Sync system clock from RTC
struct tm rtc_time;
if (rtc_get_time(&rtc_time) == ESP_OK) {
time_t epoch = mktime(&rtc_time);
struct timeval tv = { .tv_sec = epoch };
settimeofday(&tv, NULL);
ESP_LOGI("time", "System clock set from RTC: %s", asctime(&rtc_time));
}
// 2. Set timezone (read from NVS; default to UTC)
char tz_string[32] = "UTC0";
nvs_get_str(nvs_handle, "timezone", tz_string, &len);
setenv("TZ", tz_string, 1);
tzset();
NTP Callback
Register a callback that fires when NTP syncs:
#include "esp_sntp.h"
static void ntp_sync_callback(struct timeval *tv) {
// Write accurate time back to RTC
time_t utc = tv->tv_sec;
struct tm *tm_local = gmtime(&utc); // DS3231 stores UTC
rtc_set_time(tm_local);
ESP_LOGI("ntp", "NTP sync complete, RTC updated");
// Signal the main task
xEventGroupSetBits(system_events, NTP_SYNCED_BIT);
}
void ntp_init(void) {
esp_sntp_setoperatingmode(SNTP_OPMODE_POLL);
esp_sntp_setservername(0, "pool.ntp.org");
esp_sntp_set_time_sync_notification_cb(ntp_sync_callback);
esp_sntp_init();
}
Persisting Timezone
Store and retrieve timezone in NVS:
// Save (from WiFi provisioning or web UI)
nvs_handle_t h;
nvs_open("config", NVS_READWRITE, &h);
nvs_set_str(h, "timezone", "EST5EDT,M3.2.0,M11.1.0");
nvs_commit(h);
nvs_close(h);
// Load at boot
size_t len = 32;
nvs_get_str(h, "timezone", tz_string, &len);
Getting Current Local Time
After settimeofday() and tzset(), use standard POSIX time functions:
time_t now = time(NULL);
struct tm *local = localtime(&now); // local time (respects TZ)
struct tm *utc = gmtime(&now); // UTC
Use local for display; store UTC in the RTC (rtc_set_time(gmtime(&now))) to avoid
confusion during DST transitions.