import machine
from utime import sleep, ticks_ms
s0 = machine.Pin(27, machine.Pin.OUT)
s1 = machine.Pin(28, machine.Pin.OUT)
mux_out = machine.Pin(26, machine.Pin.IN, machine.Pin.PULL_DOWN)
button_pins = [
machine.Pin(16, machine.Pin.IN, machine.Pin.PULL_DOWN),
machine.Pin(17, machine.Pin.IN, machine.Pin.PULL_DOWN),
machine.Pin(18, machine.Pin.IN, machine.Pin.PULL_DOWN)
]
led_pins = [machine.Pin(i, machine.Pin.OUT) for i in range(13, 22)]
PASSCODE = [2, 1, 0]
pressed_buttons = []
debounce_time = 200
last_press_time = [0, 0, 0]
def read_mux():
binary_value = 0
for selector_val in range(4):
s0.value(selector_val & 1)
s1.value((selector_val >> 1) & 1)
sleep(0.001)
binary_value |= (mux_out.value() << selector_val)
return binary_value
def button_pressed(pin):
global pressed_buttons
button_index = button_pins.index(pin)
current_time = ticks_ms()
if current_time - last_press_time[button_index] < debounce_time:
return
last_press_time[button_index] = current_time
pressed_buttons.append(button_index)
if len(pressed_buttons) > 3:
pressed_buttons.pop(0)
print(f"Button {button_index} pressed. Current sequence: {pressed_buttons}")
if len(pressed_buttons) == 3:
validate_passcode()
def validate_passcode():
global pressed_buttons
decimal_value = read_mux()
if pressed_buttons == PASSCODE:
if 0 <= decimal_value <= 8:
led_pins[decimal_value].value(not led_pins[decimal_value].value())
print(f"✅ Correct passcode entered! Toggling LED {decimal_value}")
else:
print(f"❌ Decimal number {decimal_value} is out of range! Expected [0-8].")
else:
print(f"❌ Incorrect passcode! Entered: [1, 0, 2]. Expected: {PASSCODE}")
pressed_buttons = []
for btn in button_pins:
btn.irq(trigger=machine.Pin.IRQ_RISING, handler=button_pressed)
def main():
print(" Waiting for input...")
prev_value = -1
while True:
decimal_value = read_mux()
if decimal_value != prev_value:
print(f"Decimal representation: {decimal_value}")
prev_value = decimal_value
sleep(0.1)
if __name__ == "__main__":
main()