import machine
import time
from utime import sleep
Num_of_Selectors = 4
Num_of_BTNs = 3
Num_of_LEDs = 9
BTN_Start_ID = 16
LED_Start_ID = 8
Last_BTN_Stamp = 0
keypresses = []
def PinID(pin):
return int(str(pin)[8:11].rstrip(","))
def interrupt_callback(pin):
global Last_BTN_Stamp
current_BTN_TimeStamp = time.ticks_ms()
delta_BTN_press = current_BTN_TimeStamp - Last_BTN_Stamp
if delta_BTN_press > 200:
Last_BTN_Stamp = current_BTN_TimeStamp
keypresses.append(pin)
print(f'key press : {PinID(pin) - BTN_Start_ID}')
def main():
global keypresses
global Last_BTN_Stamp
PassCodeLength = 0
selector0 = machine.Pin(27, machine.Pin.OUT)
selector1 = machine.Pin(28, machine.Pin.OUT)
muxin = machine.Pin(26, machine.Pin.IN, machine.Pin.PULL_DOWN)
BTNs = []
for BTN_indx in range(0, Num_of_BTNs):
BTNs.append(machine.Pin(BTN_Start_ID + BTN_indx, machine.Pin.IN, machine.Pin.PULL_DOWN))
BTNs[-1].irq(trigger=machine.Pin.IRQ_FALLING, handler=interrupt_callback)
PASS_CODE = [BTNs[0], BTNs[2], BTNs[1]]
PassCodeLength = len(PASS_CODE)
out_pins = []
for out_id in range(-1, Num_of_LEDs):
out_pins.append(machine.Pin(LED_Start_ID + out_id, machine.Pin.OUT))
dev_Last = -1
while True:
binary_code = 0
for selector_value in range(Num_of_Selectors):
selector0.value(selector_value % 2)
selector1.value(selector_value // 2)
sleep(0.02)
binary_code += (pow(2, selector_value) * muxin.value())
if dev_Last != binary_code:
dev_Last = binary_code
print(f'Selected Output is: {dev_Last}')
sleep(0.1)
if len(keypresses) >= PassCodeLength:
if keypresses[:PassCodeLength] == PASS_CODE:
print('Correct!')
if binary_code <= LED_Start_ID:
print(f'toggling: {binary_code}')
out_pins[binary_code].toggle()
else:
print(f'invaild output: {binary_code}, ' + \
f'vaild range: 0-8, doing nothing')
else:
print('Wrong Passcode')
print('')
keypresses = keypresses[PassCodeLength:]
if __name__ == "__main__":
main()