from machine import Pin, PWM
import time
from LiquidCrystal import LCD1602
lcd = LCD1602(rs=10, en=11, d4=18, d5=19, d6=21, d7=22)
servo = PWM(Pin(15))
servo.freq(50)  

def set_servo_angle(angle):
    
    duty = int((angle / 180) * 6000 + 2000)  
    servo.duty_u16(duty)  
    time.sleep(0.5) 

PASSWORD = "1234"
entered_password = ""
star_pass= ""
rows = [Pin(i, Pin.OUT) for i in range(1, 5)]
cols = [Pin(i, Pin.IN, Pin.PULL_DOWN) for i in range(5, 9)]
key_map = [
    ["1", "2", "3", "A"],
    ["4", "5", "6", "B"],
    ["7", "8", "9", "C"],
    ["*", "0", "#", "D"]
]

def lock_door():
    set_servo_angle(0)  
    print("Door Locked")
    lcd.move_cursor(0,0)
    lcd.clear()
    lcd.write("Door Locked")
    

def unlock_door():
    set_servo_angle(90)  
    lcd.move_cursor(0,0)
    print("Door Unlocked")
    lcd.write("Door Unlocked")
    time.sleep(5)
    lock_door()  

def scan_keypad():
    for i, row in enumerate(rows):
        row.value(1) 
        for j, col in enumerate(cols):
            if col.value() == 1:
                time.sleep(0.5)  
                return key_map[i][j]  
        row.value(0)
    return None


lock_door()  
while True:
    key = scan_keypad()
    if key:
        print("Key Pressed:", key)
        lcd.move_cursor(0,0)
        lcd.write("Enter Password")
        
        if key.isdigit():  
            entered_password += key
            star_pass += "*"
            print(entered_password)
            lcd.move_cursor(1,0)
            lcd.write(star_pass)
        elif key == "#":  
            if entered_password == PASSWORD:
                print("Correct Password!")
                lcd.move_cursor(0,0)
                lcd.scroll_text("Correct Password")
                lcd.clear()
                unlock_door()
            else:
                print("Incorrect Password!")
                lcd.move_cursor(0,0)
                lcd.scroll_text("Incorrect Pasword")
            entered_password = ""  
        elif key == "*":  
            entered_password =""