import machine
import time
from utime import sleep
# Constants defining the hardware configuration
BUTTON_COUNT = 3 # Number of push buttons
LED_COUNT = 9 # Number of LEDs
INPUT_COUNT = 4 # Number of input pins for the mux
BUTTON_START_ID = 16
LED_GPIO_START = 7
# Variables for button presses and time tracking
last_button_time_stamp = 0
key_presses = []
# Extract the numeric pin id from the passed in Pin instance
def PinId(pin):
return int(str(pin)[8:10].rstrip(","))
# Interrupt handler for button presses
def interrupt_callback(pin):
global last_button_time_stamp
# Record the timestamp of the button press
cur_button_ts = time.ticks_ms()
button_press_delta = cur_button_ts - last_button_time_stamp
# Check if the button press is valid (time difference > 200ms)
if button_press_delta > 200:
last_button_time_stamp = cur_button_ts
key_presses.append(pin)
# Print the pressed button ID
print(f'key press: {PinId(pin) - BUTTON_START_ID}')
# Main function to initialize hardware and handle logic
def main():
global key_presses
global last_button_time_stamp
PASSCODE_LENGTH = 0
# Initialize pins for mux, buttons, and LEDs
s0 = machine.Pin(27, machine.Pin.OUT)
mux_in = machine.Pin(26, machine.Pin.IN, machine.Pin.PULL_DOWN)
buttons = []
for btn_idx in range(0, BUTTON_COUNT):
buttons.append(machine.Pin(BUTTON_START_ID + btn_idx, machine.Pin.IN, machine.Pin.PULL_DOWN))
buttons[-1].irq(trigger=machine.Pin.IRQ_FALLING, handler=interrupt_callback)
# Define passcode and calculate its length
PASS_CODE = [buttons[2], buttons[0], buttons[1]]
PASSCODE_LENGTH = len(PASS_CODE)
out_pins = []
for out_id in range(0, LED_COUNT):
out_pins.append(machine.Pin(LED_GPIO_START + out_id, machine.Pin.OUT))
last_dev = -1
# Main loop for reading inputs and handling logic
while True:
binary_code = 0
# Read the multiplexer input to determine the selected output
for selector_val in range(INPUT_COUNT):
s0.value(selector_val % 2)
sleep(0.02)
binary_code += (pow(2, selector_val) * mux_in.value())
# Print the selected output if it changes
if last_dev != binary_code:
last_dev = binary_code
print(f'selected output: {last_dev}')
sleep(0.1)
# Check if the passcode is entered correctly
if len(key_presses) >= PASSCODE_LENGTH:
if key_presses[:PASSCODE_LENGTH] == PASS_CODE:
print('correct passcode')
# Toggle the corresponding LED based on the selected output
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()
# adpted from classroom(udacity)