from machine import Pin
import time
from utime import sleep
#to handle pin interrupt
def PinId(pin, buttons, button_start_id):
# find the index of the pin in the buttons list and calculate the pin ID based on BUTTON_START_ID
button_idx = buttons.index(pin)
return button_start_id + button_idx
def interrupt_callback(pin, buttons, button_start_id):
global last_button_time_stamp
cur_button_ts = time.ticks_ms()
button_press_delta = cur_button_ts - last_button_time_stamp
if button_press_delta > 200:
last_button_time_stamp = cur_button_ts
key_presses.append(pin)
# Call the PinId to get the numeric pin
print(f'key press: {PinId(pin, buttons, button_start_id) - BUTTON_START_ID}')
def main():
sleep(0.01)
print('Program starting')
BUTTON_COUNT = 3
LED_COUNT = 9
INPUT_COUNT = 4
global BUTTON_START_ID # to make BUTTON_START_ID to interrupt_callback
BUTTON_START_ID = 16
LED_GPIO_START = 7
global key_presses, last_button_time_stamp
last_button_time_stamp = 0
key_presses = []
output_value = 0
PASSCODE_LENGTH = 0
# LED Pins define
out_pins = []
for out_id in range(0, LED_COUNT):
out_pins.append(Pin(LED_GPIO_START + out_id, Pin.OUT))
# Pushbuttons Pins define
global buttons # Make buttons to interrupt_callback
buttons = []
for btn_idx in range(0, BUTTON_COUNT):
buttons.append(Pin(BUTTON_START_ID + btn_idx, Pin.IN, Pin.PULL_DOWN))
# Pass buttons and BUTTON_START_ID to the interrupt callback
buttons[-1].irq(trigger=Pin.IRQ_FALLING,
handler=lambda pin: interrupt_callback(pin, buttons, BUTTON_START_ID))
PASS_CODE = [buttons[0], buttons[2], buttons[1]]
PASSCODE_LENGTH = len(PASS_CODE)
# Definining the GPIO pins for MUX
MUX1_OUTPUT_PIN = 26
MUX1_S0_PIN = 27
MUX1_S1_PIN = 28
mux_in = Pin(MUX1_OUTPUT_PIN, Pin.IN, Pin.PULL_DOWN)
s0 = Pin(MUX1_S0_PIN, Pin.OUT)
s1 = Pin(MUX1_S1_PIN, Pin.OUT)
last_dev = -1
while True:
# the slide switch and logic gates and muxes
binary_code = 0
for selector_val in range(INPUT_COUNT):
s1_val = (selector_val >> 1) & 1
s0_val = selector_val & 1
s1.value(s1_val)
s0.value(s0_val)
sleep(0.02)
binary_code += (pow(2, selector_val) * mux_in.value())
binary_str = "0" * (INPUT_COUNT - len(bin(binary_code)[2:])) + bin(binary_code)[2:]
#this is for the password and input from push buttons
if len(key_presses) >= PASSCODE_LENGTH:
if key_presses[:PASSCODE_LENGTH] == PASS_CODE:
print('correct passcode')
if binary_code < LED_COUNT:
print(f'toggling: {binary_code}')
out_pins[binary_code].toggle()
else:
print(f'invalid output: {binary_code}, ' + \
f'valid range: 0-{len(out_pins) - 1}, doing nothing')
else:
print('wrong passcode')
print('')
key_presses = key_presses[PASSCODE_LENGTH:]
if __name__ == "__main__":
main()