cancel(id=0): 取消 RTC 中的指定闹钟。如果没有指定 id 参数,则默认取消 id=0 的闹钟。
📓获取本地RTC时间程序代码
from machine import RTC
from machine import I2C, Pin
import time # 用于调用延时sleep函数
led =Pin(2,Pin.OUT) #板载led
# 获取本地RTC
rtc =RTC()while True:
tm = rtc.datetime() # 从RTC获取本地时间
print("Local time: ", tm) # 打印本地时间
led.value(not led.value()) # 反转LED状态
time.sleep(1) # 休眠1秒
📗设置本地RTC时间代码
from machine import RTC, Pin
import time # 用于调用延时sleep函数
led =Pin(2,Pin.OUT) #板载led
rtc =RTC()
rtc.datetime((2023,4,19,2,7,48,0,0)) # set a specific date and time
while True:
tm = rtc.datetime() # 从RTC获取本地时间
print("Local time: ", tm) # 打印本地时间
led.value(not led.value()) # 反转LED状态
time.sleep(1) # 休眠1秒
📖通过引入ntptime模块从NTP获取时间设置RTC
🔖由于时区的差异,在获取的UTC0时间基础上加8个小时。
import machine
import network
import ntptime
#importutime#Set up the RTC
rtc = machine.RTC()
# 配置wifi
ssid ="######"
password ="********"
wifi = network.WLAN(network.STA_IF)if not wifi.isconnected():
wifi.active(True)
wifi.connect(ssid, password)while not wifi.isconnected():
pass
print("Connected to Wi-Fi")
# 从NTP服务器同时时间到RTC本地
ntptime.settime()print("Time set successfully")#Get the current date and time from RTC(year, month, day, weekday, hours, minutes, seconds, subseconds)= rtc.datetime()print("Current date/time: %s/%s/%s %s:%s:%s"%(day, month, year, hours+8, minutes, seconds))