Deutsch   English 

16. Real-time Clock


RTC-Module

An external real-time clock (RTC) with a battery can be used to automatically restore the current date-time when the micro:bit is switched on. For the connection to the I2C hub either a Grove cable or a Grove plug is soldered in.

The RTC chip stores the current date-time (year, month, day, hour, minute, second, weekday). By calling set(yyyy, mm, dd, h, m, s, w) you set the current date-time. As long as the power supply by the button cell is maintained, the date-time is moved forward automatically and can be retrieved with get().

 

 

Example 1: The program first sets the date-time to a start value and then displays it periodically

# Rtc1.py
import rtc
from microbit import *
    
rtc.set(2019, 7, 11, 14, 55, 20, 2)
 
while True:
    data = rtc.get()
    display.scroll("%02d:%02d:%02d" % (data[3], data[4], data[5]))
    delay(10000)
► Copy to clipboard
 

 

Explanations of the program code:

rtc.set(2019, 7 ,11, 14, 55, 20, 2) :Sets the date-time to June 11, 2019, 14:55:20 and weekday 2 (usually Monday). After the first run, this line can be commented out, and the program shows the correct time at each start

 

NTP time server

Internet time servers offer time services for several hundred million systems worldwide. They use a standardized data format, the Network Time Protocol (NTP).

Example 2: Getting and displaying current time retrieved from  time server
To access the Internet, the ESP32 logs on to an access point, retrieves the time information in raw format first from the standard server pool.ntp.org and then in string format from the server ch.pool.ntp.org. The module ntptime is used.

# Rrc2.py
import linkup
import ntptime

linkup.connectAP("mySSID", "myPassword")
data = ntptime.getTimeRaw()
print("Current time raw:", data)
data = ntptime.getTime("ch.pool.ntp.org")
print("Current time:", data)
► Copy to clipboard
 

Explanations of the program code:

getTimeRaw(): Returns the time information as tuple (yyyy, mm, dd, h, m, s, weekday, dayofyear)


Example 3
: Setting the real-time clock using a NTP server
An NTP server can be used to synchronize the RTC. This method is often used on PCs.

# Rtc3.py
from microbit import *
import linkup
import ntptime
import rtc

print("Requesting time...")
linkup.connectAP("mySSID", "myPassword")
tme = ntptime.getTimeRaw()
print("Got:", tme)
rtc.set(tme)
 
while True:
    data = rtc.get()
    display.scroll("%02d:%02d:%02d" % (data[3], data[4], data[5]))
    delay(10000)
► Copy to clipboard
 

Explanations of the program code:

ntptime.getTimeRaw(): Returns the date-time as tuple that is used directly in rtc.set()