from machine import Pin, I2C
import time
from rotary_irq_rp2 import RotaryIRQ # RP2-specific rotary encoder library
from ssd1306 import SSD1306_I2C
# OLED setup (SSD1306, 128x64, I2C0 on GP0 and GP1)
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
oled = SSD1306_I2C(128, 64, i2c)
ROTARY_PIN_A = 18 # GP18 for CLK
ROTARY_PIN_B = 19 # GP19 for DT
BUTTON_PIN = 20 # SW
# Button setup
button = Pin(BUTTON_PIN, Pin.IN, Pin.PULL_UP)
# Menu items
menu_items = ["Start", "Settings", "About", "Exit"]
menu_index = 0 # Current menu selection
button_pressed = False
# Initialize rotary encoder
rotary = RotaryIRQ(pin_num_clk=ROTARY_PIN_A,
pin_num_dt=ROTARY_PIN_B,
min_val=0,
max_val=len(menu_items) -1,
reverse=True,
#range_mode=RotaryIRQ.RANGE_BOUNDED,
range_mode=RotaryIRQ.RANGE_WRAP,
pull_up=True,
#half_step=False)
)
# Function to draw the menu on OLED
def draw_menu():
oled.fill(0) # Clear display
for i in range(len(menu_items)):
if i == menu_index:
# Highlight selected item
oled.fill_rect(0, i * 16, 128, 16, 1) # White background
oled.text(menu_items[i], 0, i * 16, 0) # Black text
else:
oled.text(menu_items[i], 0, i * 16, 1) # White text on black
oled.show()
# Main loop
while True:
try:
# Read the current value of the rotary encoder
menu_index = rotary.value()
draw_menu() # Refresh display
# Check for button press
if button.value() == 0: # Active low
button_pressed = True
if button_pressed:
oled.fill(0) # Clear display
if menu_index == 0:
oled.text("Starting...", 0, 0, 1)
elif menu_index == 1:
oled.text("Settings:", 0, 0, 1)
elif menu_index == 2:
oled.text("About:", 0, 0, 1)
elif menu_index == 3:
oled.text("Exiting...", 0, 0, 1)
oled.show()
time.sleep(2) # Show message for 2 seconds
menu_index = 0 # Reset to "Start"
rotary.set(value=0) # Reset encoder value
button_pressed = False
time.sleep_ms(50) # Small delay to reduce CPU usage
except KeyboardInterrupt:
break