import machine
import time
from utime import sleep
BUTTONS_COUNT = 3
LEDS_COUNT = 9
INPUTS_COUNT = 4
MAX_SELECTION = 16
BUTTON_BASE = 16
LED_BASE = 7
debounce = 0
key_presses = []
def extract_id(pin):
return int(''.join(filter(str.isdigit, str(pin))))
def handle_button_interrupt(pin):
global debounce
current = time.ticks_ms()
if current - debounce > 300:
debounce = current
pin_id = extract_id(pin)
if pin_id != -1:
key_presses.append(pin_id)
print(f'You pressed {pin_id - BUTTON_BASE}')
sleep(0.1)
def leds():
global led
led = [machine.Pin(LED_BASE + i, machine.Pin.OUT) for i in range(LEDS_COUNT)]
def main():
global key_presses, debounce
PASSCODE_LENGTH = 3
mux = [
machine.Pin(27, machine.Pin.OUT),
machine.Pin(28, machine.Pin.OUT),
machine.Pin(26, machine.Pin.IN, machine.Pin.PULL_DOWN)
]
buttons = [machine.Pin(BUTTON_BASE + i, machine.Pin.IN, machine.Pin.PULL_DOWN) for i in range(BUTTONS_COUNT)]
for button in buttons:
button.irq(trigger=machine.Pin.IRQ_FALLING, handler=handle_button_interrupt)
PASS_CODE = [BUTTON_BASE, BUTTON_BASE + 2, BUTTON_BASE + 1]
leds()
last_dev = -1
while True:
binary_code = 0
stable_readings = 0
stable_value = None
while stable_readings < 3:
current_value = 0
for i in range(INPUTS_COUNT):
s0 = (i >> 0) & 1
s1 = (i >> 1) & 1
mux[0].value(s0)
mux[1].value(s1)
if mux[-1].value() == 1:
current_value |= (1 << i)
if stable_value is None:
stable_value = current_value
elif current_value == stable_value:
stable_readings += 1
else:
stable_value = current_value
stable_readings = 0
if last_dev != stable_value:
last_dev = stable_value
print(f'Selected decimal: {last_dev}')
if len(key_presses) >= PASSCODE_LENGTH:
if key_presses[:PASSCODE_LENGTH] == PASS_CODE:
if last_dev < LEDS_COUNT:
led[last_dev].toggle()
print(f'Toggle LED: {last_dev}')
elif last_dev <= MAX_SELECTION:
print(f'Out of Range it is {last_dev} (Maximum is 8)')
else:
print('Incorrect passcode')
key_presses = key_presses[PASSCODE_LENGTH:]
if __name__ == "__main__":
main()