import time
from machine import Pin
time.sleep(0.1)
# led, buzzer and feedback led creation
green_led = Pin(15, Pin.OUT)
red_led = Pin(14, Pin.OUT)
feedback_led = Pin(7, Pin.OUT)
buzzer = Pin(26, Pin.OUT)
# button creation
btn1 = Pin(9, Pin.IN, Pin.PULL_UP)
btn2 = Pin(10, Pin.IN, Pin.PULL_UP)
btn3 = Pin(21, Pin.IN, Pin.PULL_UP)
btn4 = Pin(20, Pin.IN, Pin.PULL_UP)
btn5 = Pin(19, Pin.IN, Pin.PULL_UP)
green_led.off()
red_led.off()
feedback_led.off()
buzzer.off()
correct_code = [1, 2, 3, 3, 5]
user_code = []
MAX_ATTEMPTS = 3
wrong_attempts = 0
# Time to flash the feedback LED when a button is pressed
FEEDBACK_FLASH_TIME = 0.1
def read_button():
# Reads the button value (0 = pressed, 1 = released) and returns the digit
if btn1.value() == 0:
return 1
if btn2.value() == 0:
return 2
if btn3.value() == 0:
return 3
if btn4.value() == 0:
return 4
if btn5.value() == 0:
return 5
return 0
while True:
pressed = read_button()
# buttons that are pressed are shown as pressed on the screen
if pressed != 0:
user_code.append(pressed)
print("Button", pressed, "pressed")
# Implement LED output indication of button press
feedback_led.on()
time.sleep(FEEDBACK_FLASH_TIME)
feedback_led.off()
# Debounce/wait for button release to avoid multiple readings from a single press
time.sleep(0.3)
# Automatic code check when 5 digits are entered
if len(user_code) == len(correct_code):
print("Checking code...")
# code check
print("You entered:", user_code)
if user_code == correct_code:
# Code Correct: Green LED on for 5 seconds
print("Code Correct!")
green_led.on()
time.sleep(5)
green_led.off()
user_code = []
wrong_attempts = 0
else:
wrong_attempts += 1
attempts_left = MAX_ATTEMPTS - wrong_attempts
if wrong_attempts < MAX_ATTEMPTS:
# Code Incorrect: Red LED blinks 3 times with 0.5 second gap inbetween
print("Code Incorrect: you have", attempts_left, "number of attempts left!")
for i in range(3):
red_led.on()
time.sleep(0.5)
red_led.off()
time.sleep(0.5) # Gap 0.5s
# System reset happens by clearing the code
user_code = []
else:
# System Lock: Red LED on for 3s, Buzzer on for 3s, System Reset
print("Code Incorrect, System Will Lock for 6 seconds")
red_led.on()
time.sleep(3) # Red LED remains on for 3 seconds
buzzer.on()
time.sleep(3) # Buzzer on for 3 seconds
buzzer.off()
red_led.off()
# System Locked: Green LED blinks 3 times (0.5s gap)
for i in range(3):
green_led.on()
time.sleep(0.5)
green_led.off()
time.sleep(0.5) # Gap 0.5s
print("System Reset, you have 3 attempts!")
user_code = []
wrong_attempts = 0
time.sleep(0.02)