在MicroPython 库中,提供了对RTC 类的支持。就RTC而言它是一个独立的时钟,利用它可对日期和时间进行跟踪及使用。
在使用RTC之前,必须先导入RTC,即:
from machine import RTC
然后才能加以引用,即:
rtc = RTC()
为了校正系统的 RTC时间,可通过如下语句来更新或设置系统时间,即:
rtc.datetime((2025, 9, 29, 0, 12, 58, 30, 0))
通过print语句可查看其内容,即:
print(rtc.datetime())
其输出形式为:
(2025, 6, 15, 20, 10, 30, 36, 0)
至此,就可以利用RTC实现电子时钟功能,其程序及测试结果如图1所示。
图1 程序及测试结果
在使用TFT屏显示的情况下,实现电子时钟显示效果的程序为:
from machine import UART,SPI,Pin
from ST7735 import TFT
from font import sysfont, seriffont, terminalfont
import time
import math
TFT_CLK = const(23)
TFT_MOSI = const(24)
TFT_DC = const(2)
TFT_RST = const(3)
TFT_CS = const(4)
spi = SPI(1, baudrate=80_000_000, polarity=0, phase=0, bits=8, sck=Pin(TFT_CLK), mosi=Pin(TFT_MOSI), miso=None)
tft = TFT(spi, TFT_DC, TFT_RST, TFT_CS)
tft.initg() # lcd 1.77' 128x160
tft.rotation(2);
def colock_disp():
tft.fillrect((19, 68), (95, 18), TFT.BLACK)
tft.text((20, 70), str(z[4])+":"+str(z[5])+":"+str(z[6]), TFT.PURPLE, sysfont,2,nowrap=True)
tft.fill(TFT.BLACK)
z=rtc.datetime()
tft.text((10, 40), str(z[0])+"-"+str(z[1])+"-"+str(z[2]), TFT.PURPLE, sysfont,2,nowrap=True)
p=z[6]
o=p
while True:
z=rtc.datetime()
p=z[6]
if(p!=o):
colock_disp()
o=p
time.sleep_ms(500)
经程序运行,其显示效果如图2所示。
图2 显示效果