import time
import machine
from utime import sleep
BUTTON_START_PIN = 16
LED_START_PIN = 7
BUTTON_COUNT = 3
LED_COUNT = 9
PASSCODE = [0, 2, 1]
PASSCODE_LENGTH = len(PASSCODE)
last_button_time = 0
key_presses = []
def get_pin_number(pin):
return int(str(pin)[8:11].rstrip(" , "))
def button_pressed(pin):
global last_button_time, key_presses
current_time = time.ticks_ms()
time_since_last_press = current_time - last_button_time
if time_since_last_press > 200:
last_button_time = current_time
pressed_button = get_pin_number(pin) - BUTTON_START_PIN
key_presses.append(pressed_button)
print(f'Button pressed: {pressed_button}')
def setup_mux():
s0 = machine.Pin(27, machine.Pin.OUT)
s1 = machine.Pin(28, machine.Pin.OUT)
mux_input = machine.Pin(26, machine.Pin.IN, machine.Pin.PULL_DOWN)
return s0, s1, mux_input
def setup_buttons():
buttons = []
for i in range(BUTTON_COUNT):
button = machine.Pin(BUTTON_START_PIN + i, machine.Pin.IN, machine.Pin.PULL_DOWN)
button.irq(trigger=machine.Pin.IRQ_FALLING, handler=button_pressed)
buttons.append(button)
return buttons
def setup_leds():
return [machine.Pin(LED_START_PIN + i, machine.Pin.OUT) for i in range(LED_COUNT)]
def read_mux(s0, s1, mux_input):
binary_code = 0
for selector_value in range(4):
s0.value(selector_value % 2)
s1.value(selector_value // 2)
time.sleep_ms(20)
binary_code += (2 ** selector_value) * mux_input.value()
return binary_code
def process_passcode(binary_code, leds):
global key_presses
if len(key_presses) >= PASSCODE_LENGTH:
if key_presses[:PASSCODE_LENGTH] == PASSCODE:
print('Correct passcode')
if 0 <= binary_code < LED_COUNT:
print(f'Toggling LED: {binary_code}')
leds[binary_code].toggle()
else:
print(f'Invalid output: {binary_code}, valid range: 0-{LED_COUNT - 1}')
else:
print('Wrong passcode')
key_presses = key_presses[PASSCODE_LENGTH:]
def main():
global key_presses
s0, s1, mux_input = setup_mux()
buttons = setup_buttons()
leds = setup_leds()
last_selected_device = -1
while True:
binary_code = read_mux(s0, s1, mux_input)
if last_selected_device != binary_code:
last_selected_device = binary_code
print(f'Selected output: {last_selected_device}')
process_passcode(binary_code, leds)
time.sleep_ms(100)
if __name__ == "__main__":
main()