from machine import Pin, I2C, ADC
import time
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
# ---------------- LCD SETUP ----------------
I2C_ADDR = 0x27
i2c = I2C(0, scl=Pin(1), sda=Pin(0), freq=400000)
lcd = I2cLcd(i2c, I2C_ADDR, 4, 20)
# ---------------- HARDWARE ----------------
leds = [Pin(2, Pin.OUT), Pin(3, Pin.OUT), Pin(4, Pin.OUT)]
btn1 = Pin(5, Pin.IN, Pin.PULL_DOWN)
test_btn = Pin(6, Pin.IN, Pin.PULL_DOWN)
buzzer = Pin(15, Pin.OUT)
pot = ADC(26)
# Rotary encoder
clk = Pin(16, Pin.IN, Pin.PULL_DOWN)
dt = Pin(17, Pin.IN, Pin.PULL_DOWN)
sw = Pin(18, Pin.IN, Pin.PULL_DOWN)
# ---------------- STATE ----------------
current_exp = 0
max_exp = 5
experiments = [
"LED Blink",
"Button Debounce",
"ADC Reading",
"Serial Comm",
"LCD Test",
"Buzzer Test"
]
# ---------------- LCD DISPLAY ----------------
def show_menu():
lcd.clear()
lcd.putstr("Trainer Kit\n")
lcd.putstr("Exp: {}\n".format(experiments[current_exp]))
lcd.putstr("Rotate + TEST")
# ---------------- ROTARY ENCODER ----------------
last_clk = clk.value()
def read_encoder():
global current_exp, last_clk
if clk.value() != last_clk:
if dt.value() != clk.value():
current_exp += 1
else:
current_exp -= 1
# wrap around
if current_exp > max_exp:
current_exp = 0
if current_exp < 0:
current_exp = max_exp
show_menu()
last_clk = clk.value()
# ---------------- EXPERIMENT FUNCTIONS ----------------
def exp1_led():
for _ in range(5):
for led in leds:
led.on()
time.sleep(0.1)
led.off()
def exp2_debounce():
count = 0
start = time.time()
while time.time() - start < 3:
if btn1.value():
count += 1
time.sleep(0.2) # debounce delay
return count
def exp3_adc():
val = pot.read_u16()
print("ADC Value:", val)
return val
def exp4_serial():
print("Serial Communication Working ✔")
return True
def exp5_lcd():
lcd.clear()
lcd.putstr("LCD TEST OK\nLine 2 Active")
return True
def exp6_buzzer():
buzzer.on()
time.sleep(0.3)
buzzer.off()
return True
# ---------------- TEST SYSTEM ----------------
def run_test():
lcd.clear()
lcd.putstr("Testing...\n")
result = False
if current_exp == 0:
exp1_led()
result = True
elif current_exp == 1:
result = exp2_debounce() > 0
elif current_exp == 2:
val = exp3_adc()
result = val > 1000
elif current_exp == 3:
result = exp4_serial()
elif current_exp == 4:
result = exp5_lcd()
elif current_exp == 5:
result = exp6_buzzer()
lcd.clear()
if result:
lcd.putstr("PASS\nExperiment OK")
print("RESULT: PASS")
else:
lcd.putstr("FAIL\nCheck Setup")
print("RESULT: FAIL")
time.sleep(2)
show_menu()
# ---------------- MAIN LOOP ----------------
show_menu()
while True:
read_encoder()
if test_btn.value():
run_test()
time.sleep(0.5)