Syncronise ESP32 RTC using NTP and setting timezone from NVS

This document carries on from Wifi using the ESP-IDF - since you'd need an internet connetion to use NTP and NVS to store the local timezone.

This will syncronise the ESP32 RTC using NTP - no need for a battery backup or a way to set the initial time. pool.ntp.org is hardcoded, there are options to use the DHCP assigned NTP, but the public ntp host is distributed amoung many A records, possibly even geographically and the code only queries it every few hours.

Localisation (based on a TimeZone) is stored outside the application in the ntp NVS namespace using the tz key. How the TimeZone is described is beyond the scope of this example./p>

It is possible that having this

summarised as a video
might help.

Prepare NVS (create partition)

see Wifi using the ESP-IDF.

Create an nvs.csv file and flash that to the nvs

esp32]# joe nvs.csv
key,type,encoding,value
wifi,namespace,,
SKYXXXXX,data,string,r5w9wokdcnkf
SKYXXXXX,data,string,yuXWfV8j89sd
ntp,namespace,,
tz,data,string,SAST-2

create a bin file and flash this to the ESP32.

esp32]# nvs_partition_gen.py generate nvs.csv nvs.bin 0x3000

Creating NVS binary with version: V2 - Multipage Blob Support Enabled

Created NVS binary: ===> nvs.bin
esp32]# parttool.py -p /dev/ttyACM0 write_partition --partition-name=nvs --input "nvs.bin"
...
Written contents of file 'nvs.bin' at offset 0x9000
esp32]#

Application

Add .c code for the wifi functions and app_main

esp32]# cd wifi 
esp32/wifi]# joe ../wifi.lib.c
esp32/wifi]# joe main/wifi.c

Compile and flash this to the ESP32

esp32/wifi]# idf.py -p /dev/ttyACM0 flash monitor

It should start up, connect to a wifi network and immediately attempt to synctronise the RTC via NTP, setting the timezone to the value of the ntp.tz key written into NVS above.

 


last modified: 2025-09-30 08:19:44