from machine import Pin, ADC, I2C
import utime
from lcd_api import LcdApi
from pico_i2c_lcd import I2cLcd
# -------- LCD SETUP --------
I2C_ADDR = 0x27 # change to 0x3F if needed
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
lcd = I2cLcd(i2c, I2C_ADDR, 2, 16)
# -------- JOYSTICK --------
xAxis = ADC(Pin(27))
yAxis = ADC(Pin(26))
button = Pin(16, Pin.IN, Pin.PULL_UP)
# -------- VARIABLES --------
activated = False
level = 0 # volume level (0–16)
prev_direction = "CENTER"
# -------- FUNCTION --------
def get_direction(x, y):
# Adjusted thresholds (important)
if x < 20000:
return "LEFT"
elif x > 45000:
return "RIGHT"
elif y < 20000:
return "UP"
elif y > 45000:
return "DOWN"
else:
return "CENTER"
def draw_bar(level):
lcd.move_to(0, 1)
bar = "#" * level + " " * (16 - level)
lcd.putstr(bar)
# -------- START --------
lcd.clear()
lcd.putstr("Press Button")
while True:
btn = button.value()
# -------- ACTIVATE SYSTEM --------
if not activated:
if btn == 0:
activated = True
lcd.clear()
lcd.putstr("READY")
utime.sleep(1)
lcd.clear()
lcd.putstr("Volume:")
else:
x = xAxis.read_u16()
y = yAxis.read_u16()
direction = get_direction(x, y)
# -------- EDGE DETECTION --------
if direction != prev_direction:
# ➡️ RIGHT → Increase volume
if direction == "RIGHT":
if level < 16:
level += 1
# ⬅️ LEFT → Decrease volume
elif direction == "LEFT":
if level > 0:
level -= 1
# ⬆️ UP
elif direction == "UP":
lcd.clear()
lcd.putstr("UP")
utime.sleep(0.5)
lcd.clear()
lcd.putstr("Volume:")
# ⬇️ DOWN
elif direction == "DOWN":
lcd.clear()
lcd.putstr("DOWN")
utime.sleep(0.5)
lcd.clear()
lcd.putstr("Volume:")
# Save direction
prev_direction = direction
# Draw volume bar
draw_bar(level)
utime.sleep(0.05) # fast + smooth