from machine import Pin, I2C
import ssd1306
import time
# Code optimisé (embarqué)
# Principe du menu
"""
Bouton UP → monte dans le menu
Bouton DOWN → descend
Bouton OK → valide
"""
from machine import Pin, I2C
import ssd1306
import time
# -------- Constantes --------
OLED_W = 128
OLED_H = 64
LINE_H = 10
DEBOUNCE_MS = 180
# -------- OLED --------
i2c = I2C(0, scl=Pin(17), sda=Pin(16))
oled = ssd1306.SSD1306_I2C(OLED_W, OLED_H, i2c)
# -------- Boutons --------
btn_up = Pin(2, Pin.IN, Pin.PULL_UP)
btn_down = Pin(3, Pin.IN, Pin.PULL_UP)
btn_ok = Pin(4, Pin.IN, Pin.PULL_UP)
# -------- Menu --------
MENU = ("Status", "Settings", "Test IO", "About")
menu_len = len(MENU)
cursor = 0
# -------- États --------
STATE_MENU = 0
STATE_ACTION = 1
state = STATE_MENU
# -------- Timing --------
last_time = 0
need_redraw = True
# -------- Fonctions --------
def pressed(btn):
global last_time
now = time.ticks_ms()
if not btn.value() and time.ticks_diff(now, last_time) > DEBOUNCE_MS:
last_time = now
return True
return False
def draw_menu():
oled.fill(0)
for i in range(menu_len):
y = i * LINE_H
if i == cursor:
oled.text(">", 0, y)
oled.text(MENU[i], 10, y)
oled.show()
def draw_action(text):
oled.fill(0)
oled.text("Selected:", 0, 0)
oled.text(text, 0, 12)
oled.show()
# -------- Boucle principale --------
while True:
if state == STATE_MENU:
if pressed(btn_up):
cursor = (cursor - 1) % menu_len
need_redraw = True
elif pressed(btn_down):
cursor = (cursor + 1) % menu_len
need_redraw = True
elif pressed(btn_ok):
state = STATE_ACTION
need_redraw = True
if need_redraw:
draw_menu()
need_redraw = False
elif state == STATE_ACTION:
draw_action(MENU[cursor])
time.sleep_ms(600)
state = STATE_MENU
need_redraw = True
time.sleep_ms(10)