import machine
import time
from utime import sleep
# Define LED variables
LED_COUNT = 9
LED_START = 12
LED_LIST = []
# Define button variables
BUTTON_COUNT = 3
BUTTON_START = 6
BUTTON_LIST = []
BUTTON_PRESSED = []
# Define SELECTOR pins
SELECT0 = machine.Pin(22, machine.Pin.OUT)
SELECT1 = machine.Pin(26, machine.Pin.OUT)
MUX_IN = machine.Pin(20, machine.Pin.IN, machine.Pin.PULL_DOWN)
# Define passcode and tracking variables
CORRECT_PASSCODE = [2, 0, 1]
PASSCODE_LENGTH = len(CORRECT_PASSCODE)
start_time = 0
# Function to handle button press interrupts
def interrupt_callback(pin):
global start_time, BUTTON_PRESSED
current_time = time.ticks_ms()
if (current_time - start_time) > 200: # Debounce (200ms)
start_time = current_time
button_index = BUTTON_LIST.index(pin)
BUTTON_PRESSED.append(button_index) # Store button index
print(f"Button pressed: {button_index}")
print(f"Current sequence: {BUTTON_PRESSED}")
# Initialize buttons and attach interrupts
for i in range(BUTTON_COUNT):
button_pin = machine.Pin(BUTTON_START + i, machine.Pin.IN, machine.Pin.PULL_DOWN)
BUTTON_LIST.append(button_pin)
button_pin.irq(trigger=machine.Pin.IRQ_FALLING, handler=interrupt_callback)
# Initialize LEDs
for i in range(LED_COUNT):
led = machine.Pin(LED_START + i, machine.Pin.OUT)
LED_LIST.append(led)
# Function to check passcode
def check_passcode():
global BUTTON_PRESSED
if len(BUTTON_PRESSED) >= PASSCODE_LENGTH:
if BUTTON_PRESSED[:PASSCODE_LENGTH] == CORRECT_PASSCODE:
print("✅ Correct Passcode! Unlocking system.")
for led in LED_LIST:
led.value(1) # Turn all LEDs ON
sleep(1)
for led in LED_LIST:
led.value(0) # Turn all LEDs OFF
else:
print("❌ Incorrect Passcode. Try Again.")
BUTTON_PRESSED = [] # Reset input
# Function to read selector switch and control LEDs
def read_selector():
last_value = -1
while True:
binary_code = 0
for selector_val in range(4): # 2-bit selector (0 to 3)
SELECT0.value(selector_val % 2)
SELECT1.value(selector_val // 2)
sleep(0.02)
binary_code += (pow(2, selector_val) * MUX_IN.value())
if last_value != binary_code:
last_value = binary_code
print(f"Selected output: {binary_code}")
sleep(0.1)
if len(BUTTON_PRESSED) >= PASSCODE_LENGTH:
check_passcode()
# Main function
def main():
print("System Initialized. Waiting for input...")
read_selector()
if __name__ == "__main__":
main()