from machine import Pin, I2C
import ssd1306
import time
import framebuf
"""
日志输入端口: LOGS.append("日志内容") 显示日志长度: 16
"""
# OLED 初始化
i2c0 = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c0)
# 按键 初始化
P00 = Pin(4, Pin.IN, Pin.PULL_UP)
P01 = Pin(3, Pin.IN, Pin.PULL_UP)
P02 = Pin(2, Pin.IN, Pin.PULL_UP)
# LED 初始化
L0 = Pin(5, Pin.OUT)
# OLED控制区域显示+列表自动换行
BOX_X = 2
BOX_Y = 14
BOX_W = 124
BOX_H = 48
buf = bytearray(BOX_W * BOX_H // 8)
fb = framebuf.FrameBuffer(buf, BOX_W, BOX_H, framebuf.MONO_VLSB)
def text_control(LOGS_):
sty_y = 0
fb.fill(0)
for i in LOGS_:
i = str(i)
fb.text(i, 0, sty_y, 1)
sty_y += 8
if sty_y >= BOX_H:
break
oled.blit(fb, BOX_X, BOX_Y)
# LOG 显示管理
LOGS = ["boot ok."]
def LOGS_input():
if len(LOGS) > 6:
LOGS.pop(0)
text_control(LOGS)
# 按键防抖+LED反馈
def pressed(pin):
if pin.value() == 0:
L0.value(1)
time.sleep_ms(10)
L0.value(0)
if pin.value() == 0:
return True
return False
# 按键输入检测
def key_input():
global LOGS
if pressed(P00):
print("00")
if pressed(P01):
print("01")
if pressed(P02):
print("02")
# 按键按住计时(ms)
start = [0,0,0]
time_val = [0,0,0]
keys = [P00,P01,P02]
def key_timer():
global time_val
for i,p in enumerate(keys):
if not p.value():
if start[i]==0:
start[i] = time.ticks_ms()
else:
if start[i]:
time_val[i] = time.ticks_ms()-start[i]
print(f"P0{i}={time_val[i]}")
start[i]=0
# OLED反色显示文字
def text_invert(char, x, y):
x_ = len(char) * 8
oled.fill_rect(x, y, x_, 8, 1)
oled.text(char, x, y, 0)
# FPS获取
FPS = 0
FPS_Print = "XX"
TMS = time.ticks_ms()
def FPS_Get():
global FPS, FPS_Print, TMS
FPS += 1
if time.ticks_ms() - TMS >= 1000:
FPS_Print = str(FPS)
FPS = 0
TMS = time.ticks_ms()
# 菜单0 UI
def ui_zero():
oled.fill(0)
text_invert("-liuxia-", 0, 0)
oled.text(f"FPS:{FPS_Print}", 79, 0, 1)
oled.rect(0,9,128,1,1)
oled.rect(1,12,126,51,1)
oled.rect(0,11,32,1,1)
oled.rect(0,63,32,1,1)
oled.rect(0,11,1,52,1)
oled.rect(96,11,32,1,1)
oled.rect(96,63,32,1,1)
oled.rect(127,11,1,52,1)
FPS_Get()
key_input()
key_timer()
if start[0] != 0 and time.ticks_ms() - start[0] > 200:
jishi_ms = 3000 - (time.ticks_ms() - start[0])
jishi_s = jishi_ms / 1000
oled.fill_rect(22, 17, 82, 30, 1)
oled.fill_rect(22, 19, 82, 1, 0)
oled.fill_rect(22, 21, 82, 1, 0)
oled.fill_rect(22, 45, 82, 1, 0)
oled.fill_rect(22, 43, 82, 1, 0)
oled.text(f"menu:{jishi_s:.2f}s", 23, 28, 0)
if jishi_ms <= 0:
jishi_ms = 0
start[0] = 0
run_flags[0] = "no"
run_flags[1] = "yes"
else:
LOGS_input()
oled.show()
# 菜单1 UI
def ui_one():
oled.fill(0)
text_invert("-liuxia-", 0, 0)
oled.text(f"FPS:{FPS_Print}", 79, 0, 1)
oled.rect(0,9,128,1,1)
key_input()
key_timer()
oled.show()
run_flags = ["yes", "no", "no"]
# 运行窗口
while run_flags[0] == "yes":
ui_zero()
while run_flags[1] == "yes":
ui_one()