import machine
from utime import sleep, ticks_ms
button_base_pin = 16
correct_sequence = [0, 2, 1]
mux_sel_0 = machine.Pin(28, machine.Pin.OUT)
mux_sel_1 = machine.Pin(27, machine.Pin.OUT)
mux_input = machine.Pin(26, machine.Pin.IN, machine.Pin.PULL_DOWN)
leds = [machine.Pin(i, machine.Pin.OUT) for i in range(7, 16)]
input_sequence = []
current_selection = -1
previous_selection = -1
last_press_time = {i: 0 for i in range(3)}
debounce_delay = 200
def read_mux():
active_bits = 0
for sel0 in range(2):
mux_sel_0.value(sel0)
for sel1 in range(2):
mux_sel_1.value(sel1)
if mux_input.value():
active_bits += 1
sleep(0.02)
return active_bits
def button_pressed(pin):
global input_sequence
button_index = buttons.index(pin)
current_time = ticks_ms()
if current_time - last_press_time[button_index] > debounce_delay:
last_press_time[button_index] = current_time
input_sequence.append(button_index)
print(f'Button {button_index} pressed')
if len(input_sequence) == 3:
verify_sequence()
buttons = [
machine.Pin(button_base_pin + i, machine.Pin.IN, machine.Pin.PULL_DOWN)
for i in range(3)
]
for button in buttons:
button.irq(trigger=machine.Pin.IRQ_RISING, handler=button_pressed)
def verify_sequence():
global input_sequence, current_selection
if input_sequence == correct_sequence:
print("Correct sequence entered")
if 0 <= current_selection < len(leds):
leds[current_selection].toggle()
print(f"LED {current_selection + 7} toggled")
else:
print(f"Selection {current_selection} out of range")
else:
print("Incorrect sequence")
input_sequence.clear()
def main():
global current_selection, previous_selection
while True:
current_selection = read_mux()
if current_selection != previous_selection:
print(f'Output = {current_selection}')
previous_selection = current_selection
sleep(0.1)
if __name__ == "__main__":
print("System initialized...")
main()