from machine import Pin, Timer, PWM, I2C
from keypad import Keypad
from ssd1306 import SSD1306_I2C
import time
placeholder = '' # For functions that require an argument
status_led = (Pin(0, Pin.OUT), Pin(27, Pin.OUT), Pin(1, Pin.OUT)) # Red, Blue, Green LEDs respectively
kp_rows = (Pin(26), Pin(22), Pin(21), Pin(20))
kp_cols = (Pin(19), Pin(18), Pin(17), Pin(16))
servo = PWM(28, freq = 50)
i2c = I2C(1, sda=Pin('GP1'), scl=Pin('GP0')) # !!!!!micropython error "ValueError: bad SCL pin"!!!!!
display = SSD1306_I2C(128, 64, i2c)
unlockCode = '24861405'
lockState = False
inputBuffer = '--------'
servo.duty_u16(4825) # Starting off
status_led[2].on() # in an
print("State = UNLOCKED") # unlocked state
keyState = ''
blink_count = 0
blinker = Timer()
while True:
display.fill(0)
display.ellipse(23,32,12,12,1,True)
display.rect(12,30,23,5,0,True)
display.text("12345678",50,20)
display.text("Locked",50,38)
display.show()
time.sleep(1)
display.fill(0)
display.ellipse(23,32,12,12,1,True)
display.rect(21,21,5,23,0,True)
display.text("24861405",50,20)
display.text("Unlocked",50,38)
display.show()
time.sleep(1)
def blink_callback(timer):
global blink_count
status_led[0].toggle()
blink_count += 1
if blink_count < 4:
blinker.init(mode=blinker.ONE_SHOT, period=200, callback=blink_callback)
else:
blink_count = 0
status_led[0].on()
def keypress(timer):
global keyState
if keyState != "":
status_led[1].on()
keyState = ""
status_led[1].off()
attempts = 0
attemptLockCount = 0
def lockAlgorithm(keyValue):
global lockState, inputBuffer, keyState, blink_count, attempts, attemptLockCount
keyState = keyValue
if lockState:
if keyValue == '#':
if inputBuffer == unlockCode:
lockState = False
print(" - Correct. State = UNLOCKED")
status_led[0].off()
servo.duty_u16(4825)
status_led[2].on()
else:
print(" - Incorrect.")
inputBuffer = "--------"
attempts += 1
if attempts < 5:
blink_callback(placeholder)
else:
attemptLockCount += 1
if attemptLockCount >= 5:
print("Too many attempts. Please contact the owner to reset this lock.") # This statement currently doesn't print
status_led[0].off()
time.sleep(86400)
print(f"Too many attempts. Try again after {attemptLockCount*5} seconds") # This statement currently doesn't print
for i in range(attemptLockCount*5):
status_led[0].toggle()
time.sleep(0.5)
status_led[0].toggle()
time.sleep(0.5)
attempts = 0
else:
inputBuffer = inputBuffer[1:] + keyValue
print(keyValue, end="")
else:
status_led[2].on()
servo.duty_u16(4825)
if keyValue == '*':
lockState = True
status_led[2].off()
servo.duty_u16(8050)
status_led[0].on()
print("Status = LOCKED")
kp = Keypad(rows = kp_rows,
columns = kp_cols,
callback = lockAlgorithm)
tmr = Timer(freq=50, callback=keypress)