RTC in Esp32 With MicroPython

ESP32 has a RTC which is an independent clock keeps tracks of the date and time.

RTC setup and read the details

from machine import RTC
import time

rtc = RTC()
rtc.init((2022,12,27,2,10,23,0,0))

while True:
    date=rtc.datetime()
    print(date)
    time.sleep(1)

The RTC info will be reset after power-off or reset, so we may need to try one of below to have the correct datetime

  • Make sure it always has power
  • Connect with another RTC, for example DS3231
  • Sync time with NTP

Sync time with NTP

In this exercise, we will try to sync the time with NTP on each boot.

  • boot.py
def do_connect():
    import network
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('<WIFI SID>', '<WIFI Password>')
        while not wlan.isconnected():
            pass
    print('network config:', wlan.ifconfig())

do_connect()

def settime():
    import machine
    import utime
    from ntptime import time
    t = time()
    print ("GMT: ",t)
    t = t + 11 * 60 * 60     # the time returned is GMT, so added extra hours for timezone.
    print ("Local",t)
    tm = utime.localtime(t)
    tm = tm[0:3] + (0,) + tm[3:6] + (0,)
    machine.RTC().datetime(tm)

settime()
  • main.py
from machine import RTC
import time

rtc = RTC()

while True:
    date=rtc.datetime()
    print(date)
    time.sleep(1)