import machine
import time
from utime import sleep
# Define pins for selectors and buttons
selector_pins = [27, 28]
button_pins = [16, 17, 18]
# Initialize selector pins
selectors = [machine.Pin(pin, machine.Pin.OUT) for pin in selector_pins]
mux_in = machine.Pin(26, machine.Pin.IN)
# Initialize button pins
buttons = [machine.Pin(pin, machine.Pin.IN, machine.Pin.PULL_DOWN) for pin in button_pins]
# Dictionary to map button objects to their numeric IDs
btns_numeric_dict = {buttons[0]: 0, buttons[1]: 1, buttons[2]: 2}
# Pin interrupt handler function
def interrupt_callback(pin):
global bounce_time
global pressed_btns
global last_btn_pressed_time
current_time = time.ticks_ms()
if current_time - last_btn_pressed_time > bounce_time:
last_btn_pressed_time = current_time
print(f"Pressed Button Numeric ID: Button {btns_numeric_dict[pin]}")
pressed_btns.append(btns_numeric_dict[pin])
# Function to decode the binary value from selectors
def decoding():
binary_code = 0
for selector_val in range(4):
selectors[0].value(selector_val % 2)
selectors[1].value(selector_val // 2)
sleep(0.020)
binary_code += (pow(2, selector_val) * mux_in.value())
return binary_code
# Main function
def main():
global binary_num
global pressed_btns
global last_btn_pressed_time
global bounce_time
# Initialize variables
bounce_time = 200
last_btn_pressed_time = -1
pressed_btns = []
# Initial message
print('Program starting')
# Decode initial value
binary_num = decoding()
print(f"The Current Decimal Number From Switches is: {binary_num}")
# Assign interrupt handlers to buttons
for button in buttons:
button.irq(trigger=machine.Pin.IRQ_RISING, handler=interrupt_callback)
# Password for LED toggling
password = [0, 2, 1]
# Initialize LED pins
led_count = 9
led_start = 7
led_pins = range(led_start, led_start + led_count)
leds = [machine.Pin(pin, machine.Pin.OUT) for pin in led_pins]
while True:
if binary_num != decoding():
binary_num = decoding()
print(f"The Current Decimal Number From Switches is: {binary_num}")
if len(pressed_btns) == len(password):
if pressed_btns == password:
led_id = decoding()
if led_id < led_count:
leds[led_id].toggle()
print(f"Now the led {led_id } is toggled.")
else:
print("Out Of Range, Please make sure that you are in range between [0, 8]")
else:
print("Incorrect Password, Please Try again")
pressed_btns = []
if __name__ == "__main__":
main()