from keypad import Keypad
from machine import Pin, PWM
import time
secretCode = '24856059'
isLocked = False
inbuffer = "--------"
failedAttempts = 0 # Starting point
maxAttempts = 3 # Max attempts before lockout
lockoutTime = 10 # Lockout for seconds
pwm = PWM(Pin(10),freq = 50) # PWM output to control servo position
led1 = Pin(0, Pin.OUT) # Set Up LEDs, led1 (blue) indicates a key is pressed
led2 = Pin(1, Pin.OUT) # led2 (red) indicates state = locked
led3 = Pin(2, Pin.OUT) # led3 (green) indicates state = unlocked
led4 = Pin(28, Pin.OUT) # led4 (amber) indicates lockdown
def keyPressed(keyValue):
global isLocked, inbuffer, failedAttempts # Global variables are stored between function calls
led1.on() # led1 Turns on for 0.1 seconds when a key is pressed
time.sleep(0.1)
led1.off()
if isLocked:
if keyValue == '#': # User is trying to unlock
if inbuffer == secretCode: # Success only if the code matches
isLocked = False
failedAttempts = 0
pwm.duty_u16(1600) # Sets the Servo to Vertical for unlocked
led3.on() # LEDs Change accordingly if succesfully unlocked
led2.off()
led4.off()
print(" - Correct, State = UNLOCKED")
else:
print(" - Incorrect code.") # if code is wrong, message is printed, Failed attempts is +1 (ref. python functions), and LED change accordingly
failedAttempts += 1
led2.on()
led3.off()
led4.off()
if failedAttempts >= maxAttempts: #if failedAttempts >= 3, lockout occurs and message is printed when a key is pressed
print("TOO MANY FAILED ATTEMPTS - LOCKED OUT for", lockoutTime, "seconds")
failedAttempts = 0 # reset for next round
led4.on()
time.sleep(lockoutTime) # Freeze system
inbuffer = "--------" # Wrong code so reset the buffer
else: # New number needs storing in the buffer:
inbuffer = inbuffer[1:] + keyValue # Move buffer to the left and add new value
print(keyValue, end="")
elif keyValue == '*': # Unlocked and '*' pressed so change the
isLocked = True # state to locked.
pwm.duty_u16(4825) # Sets the Servo to Horizontal for Unlocked (ref. servo datasheet)
led2.on()
led3.off()
led4.off()
print("State = LOCKED")
# Setup keypad object with the correct pins and with keyPressed() as the callback function
kp = Keypad(rows = (Pin(26), Pin(22), Pin(21), Pin(20)),
columns = (Pin(19), Pin(18), Pin(17), Pin(16)),
callback = keyPressed)