from machine import Pin, I2C, PWM
from time import sleep
from pico_i2c_lcd import I2cLcd
# LCD Setup
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
lcd = I2cLcd(i2c, i2c.scan()[0], 2, 16)
# Keypad Setup
ROWS, COLS = [5, 6, 7, 8], [1, 2, 3, 4]
KEY_MAP = [["D", "#", "0", "*"], ["C", "9", "8", "7"], ["B", "6", "5", "4"], ["A", "3", "2", "1"]]
rows = [Pin(r, Pin.OUT, value=1) for r in ROWS]
cols = [Pin(c, Pin.IN, Pin.PULL_UP) for c in COLS]
# Servo Setup (for Lock)
servo = PWM(Pin(15), freq=50)
# Password Config
PASSWORD = "123"
entered = ""
def read_key():
for r, row in enumerate(rows):
row.low()
for c, col in enumerate(cols):
if not col.value():
while not col.value(): pass # Wait for release
row.high()
return KEY_MAP[r][c]
row.high()
def unlock():
lcd.clear()
lcd.putstr("Unlocked!")
servo.duty_u16(8000) # Open Lock
sleep(3)
servo.duty_u16(2000) # Lock again
lcd.clear()
lcd.putstr("Enter Code:")
# Main Loop
lcd.putstr("Enter Code:")
while True:
key = read_key()
if key:
if key in "0123456789":
entered += key
lcd.putstr("*") # Hide input
if len(entered) == 3:
if entered == PASSWORD:
unlock()
else:
lcd.clear()
lcd.putstr("Wrong Code!")
sleep(2)
lcd.clear()
lcd.putstr("Enter Code:")
entered = "" # Reset input