from keypad import Keypad
from machine import Pin, PWM, SPI
import time
from max7219 import DotMatrix # Import the DotMatrix driver
secretCode = '24856059'
isLocked = False
inbuffer = "--------"
print("State = UNLOCKED")
failedAttempts = 0
maxAttempts = 3
lockoutUntil = 0 # timestamp when lockout ends
lockoutTime = 10 # seconds
pwm = PWM(Pin(10),freq = 50) # PWM output to control servo position
spi = SPI(0, sck=Pin(2), mosi=Pin(3), miso=Pin(4)) # Intialize the SPI
cs = Pin(5) # Create CS pin
display = DotMatrix(spi, cs, 4, True) # Create MAX7129 DotMatrix driver for 4 displays
display.setBrightness(10) # Needed in real-life (virtual display ignores this)
def keyPressed(keyValue):
global isLocked, inbuffer, failedAttempts, lockoutUntil # Global variables are stored between function calls
if time.time() < lockoutUntil:
print("LOCKED OUT, TRY AGAIN IN:", int(lockoutUntil - time.time()), "seconds")
return
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(8050)
print(" - Correct, State = UNLOCKED")
else:
print(" - Incorrect code.")
failedAttempts += 1
if failedAttempts >= maxAttempts:
lockoutUntil = time.time() + lockoutTime
print("TOO MANY FAILED ATTEMPTS - LOCKED OUT for", lockoutTime, "seconds")
failedAttempts = 0 # reset for next round
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(1600)
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)