import machineimport utime# 定义PCF8563 I2C地址PCF8563_I2C_ADDR = 0x51# 初始化I2C总线i2c = machine.I2C(0, scl=machine.Pin(1), sda=machine.Pin(0), freq=100000)def bcd_to_decimal(bcd): """将BCD码转换为十进制数值""" return (bcd // 16) * 10 + (bcd % 16)def decimal_to_bcd(decimal): """将十进制数值转换为BCD码""" return (decimal // 10) * 16 + (decimal % 10)def read_rtc_time(): """读取RTC模块的时间""" i2c.writeto(PCF8563_I2C_ADDR, bytes([0x02])) # 设置读取起始地址 data = i2c.readfrom(PCF8563_I2C_ADDR, 7) # 读取7个字节的时间数据 seconds = bcd_to_decimal(data[0] & 0x7F) minutes = bcd_to_decimal(data[1] & 0x7F) hours = bcd_to_decimal(data[2] & 0x3F) day = bcd_to_decimal(data[3] & 0x3F) weekday = bcd_to_decimal(data[4] & 0x07) month = bcd_to_decimal(data[5] & 0x1F) year = bcd_to_decimal(data[6]) + 2000 return (year, month, day, hours, minutes, seconds, weekday)def set_rtc_time(year, month, day, hours, minutes, seconds, weekday): """设置RTC模块的时间""" data = bytearray(8) data[0] = 0x00 # 控制字节,清除停止位 data[1] = decimal_to_bcd(seconds) data[2] = decimal_to_bcd(minutes) data[3] = decimal_to_bcd(hours) data[4] = decimal_to_bcd(day) data[5] = decimal_to_bcd(weekday) data[6] = decimal_to_bcd(month) data[7] = decimal_to_bcd(year % 100) i2c.writeto(PCF8563_I2C_ADDR, data) # 写入时间数据# 读取RTC模块的时间year, month, day, hours, minutes, seconds, weekday = read_rtc_time()print("当前时间:{}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(year, month, day, hours, minutes, seconds))# 等待1秒utime.sleep(1)# 设置RTC模块的时间为当前时间+1秒set_rtc_time(year, month, day, hours, minutes, seconds + 1, weekday)print("时间已设置")# 再次读取RTC模块的时间,确认是否设置成功year, month, day, hours, minutes, seconds, weekday = read_rtc_time()print("新的时间:{}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(year, month, day, hours, minutes, seconds))
请尝试运行上述代码,并根据你的需求修改和扩展。希望对你有所帮助!