import time
from machine import I2C, Pin
from ssd1306 import SSD1306_I2C
# 按钮定义
bt1 = Pin(2, Pin.IN, Pin.PULL_UP) # 切换设置项
bt2 = Pin(3, Pin.IN, Pin.PULL_UP) # 增加
bt3 = Pin(4, Pin.IN, Pin.PULL_UP) # 减少
# OLED 初始化
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=200000)
oled = SSD1306_I2C(128, 64, i2c)
# 时间变量
hour = 12
minute = 0
second = 0
setting_mode = False # 是否处于设置模式
setting_item = 0 # 0:小时 1:分钟 2:秒
last_bt1 = 1
last_bt2 = 1
last_bt3 = 1
last_update = time.ticks_ms()
def draw_time(h, m, s, item):
oled.fill(0)
time_str = "{:02d}:{:02d}:{:02d}".format(h, m, s)
oled.text("Set Time:", 0, 0)
oled.text(time_str, 0, 20)
# 下划线当前设置项(每个字符宽8像素)
x_pos = [0, 8*3, 8*6][item] # 时:0, 分:24, 秒:48
oled.hline(x_pos, 36, 8*2, 1) # 下划线宽16像素,对应2位数字
oled.show()
def draw_clock(h, m, s):
oled.fill(0)
time_str = "{:02d}:{:02d}:{:02d}".format(h, m, s)
oled.text("Clock", 0, 0)
oled.text(time_str, 0, 20)
oled.show()
while True:
# 按钮读取
cur_bt1 = bt1.value()
cur_bt2 = bt2.value()
cur_bt3 = bt3.value()
# 按钮1:切换设置项/进入/退出设置模式
if last_bt1 == 1 and cur_bt1 == 0:
if not setting_mode:
setting_mode = True
setting_item = 0
else:
setting_item += 1
if setting_item > 2:
setting_mode = False # 退出设置模式
last_bt1 = cur_bt1
# 按钮2:增加
if last_bt2 == 1 and cur_bt2 == 0 and setting_mode:
if setting_item == 0:
hour = (hour + 1) % 24
elif setting_item == 1:
minute = (minute + 1) % 60
elif setting_item == 2:
second = (second + 1) % 60
last_bt2 = cur_bt2
# 按钮3:减少
if last_bt3 == 1 and cur_bt3 == 0 and setting_mode:
if setting_item == 0:
hour = (hour - 1) % 24
elif setting_item == 1:
minute = (minute - 1) % 60
elif setting_item == 2:
second = (second - 1) % 60
last_bt3 = cur_bt3
# 显示
if setting_mode and setting_item <= 2:
draw_time(hour, minute, second, setting_item)
else:
draw_clock(hour, minute, second)
# 更新时间
if time.ticks_diff(time.ticks_ms(), last_update) >= 1000:
last_update = time.ticks_ms()
second += 1
if second >= 60:
second = 0
minute += 1
if minute >= 60:
minute = 0
hour = (hour + 1) % 24
time.sleep(0.05)