from machine import Pin, I2C
import ssd1306
import time
# I2C 初始化 (SDA=GP4, SCL=GP5)
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# 开机计时起点
start_ms = time.ticks_ms()
# 画矩形边框
def draw_rect(x, y, w, h):
oled.hline(x, y, w, 1) # 顶边
oled.hline(x, y+h-1, w, 1) # 底边
oled.vline(x, y, h, 1) # 左边
oled.vline(x+w-1, y, h, 1) # 右边
# 字符居中显示函数
def draw_text_center(text, y, oled_width=128):
text_width = len(text) * 8 # 每个字符占8像素宽度
x = (oled_width - text_width) // 2 # 计算居中x坐标
oled.text(text, x, y)
# 获取累计时间(年-月-日 时:分:秒.毫秒)
def get_elapsed_ms():
diff_ms = time.ticks_diff(time.ticks_ms(), start_ms)
ms = diff_ms % 1000
sec = (diff_ms // 1000) % 60
minute = (diff_ms // 60000) % 60
hour = (diff_ms // 3600000) % 24
day = (diff_ms // 86400000) % 30
month = (diff_ms // 2592000000) % 12
year = diff_ms // 31536000000
return year, month, day, hour, minute, sec, ms
# ------------------- 主循环 -------------------
while True:
y, mo, d, h, mi, s, ms = get_elapsed_ms()
oled.fill(0) # 清屏
# 1. 全屏外边框
draw_rect(2, 2, 124, 60)
# 2. 标题(精准居中)
draw_text_center("-Pi Pico-", 8)
# 3. 日期(精准居中)
date_str = "{:04d}-{:02d}-{:02d}".format(y, mo, d)
draw_text_center(date_str, 25)
# 分隔线(居中)
oled.hline(10, 38, 108, 1)
# 4. 时间(精准居中)
time_str = "{:02d}:{:02d}:{:02d}.{:03d}".format(h, mi, s, ms)
draw_text_center(time_str, 45)
oled.show()
time.sleep_ms(1) # 1ms刷新一次