from machine import Pin, Timer, PWM
import time
#LEDs pins
green = Pin(14, Pin.OUT)
red = Pin(15, Pin.OUT)
#Servo Pins
servo = PWM(Pin(13))
servo.freq(50)
def unlock_servo():
servo.duty_u16(2000) #Unlocked
time.sleep(0.5)
def lock_servo():
servo.duty_u16(5000) #Locked
time.sleep(0.5)
#Start locked
lock_servo()
#Lock state
is_locked = True
#Code
correct_code = "23681190"
entered = ""
#Keypad wiring
rowPins = (
Pin(26, Pin.IN, Pin.PULL_UP),
Pin(22, Pin.IN, Pin.PULL_UP),
Pin(21, Pin.IN, Pin.PULL_UP),
Pin(20, Pin.IN, Pin.PULL_UP)
)
colPins = (
Pin(19, Pin.OUT),
Pin(18, Pin.OUT),
Pin(17, Pin.OUT),
Pin(16, Pin.OUT)
)
for c in colPins:
c.value(1)
#Keypad values
keyValues = ("123A", "456B", "789C", "*0#D")
keyStates = [
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]
]
def process_key(key):
global entered, is_locked
print("Key:", key)
#Ignore A B C D
if key in "ABCD":
return
#Clears what was written previously
if key == "*":
entered = ""
red.value(1)
time.sleep(0.2)
red.value(0)
#Locking when * is pressed system is unlocked
if not is_locked:
lock_servo()
is_locked = True
print("Locked")
return
#Entering the password
if key == "#":
if entered == correct_code and is_locked:
print("Code correct")
green.value(1)
unlock_servo()
time.sleep(1)
green.value(0)
is_locked = False
print("Unlocked")
else:
print("Code incorrect")
red.value(1)
time.sleep(0.5)
red.value(0)
entered = ""
return
#Adds numbers into a string
if key.isdigit():
entered += key
if len(entered) > len(correct_code):
entered = entered[-len(correct_code):]
#Keypad scanner
def scanKeys(timer):
for col in range(4):
colPins[col].value(0)
for row in range(4):
val = rowPins[row].value()
if val != keyStates[row][col]:
keyStates[row][col] = val
if val == 0:
key = keyValues[row][col]
process_key(key)
colPins[col].value(1)
#Timer
tmr = Timer(freq=100, callback=scanKeys)
#Loop
while True:
time.sleep(1)