from machine import Pin, PWM, I2C
import utime
from pico_i2c_lcd import I2cLcd
pwm = PWM(Pin(14))
pwm.freq(50)
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
I2C_ADDR = i2c.scan()[0]
lcd = I2cLcd(i2c, I2C_ADDR, 2, 16)

matrix_keys = [['1', '2', '3', 'A'],
               ['4', '5', '6', 'B'],
               ['7', '8', '9', 'C'],
               ['*', '0', '#', 'D']]
keypad_rows = [9, 8, 7, 6]
keypad_columns = [5, 4, 3, 2]

col_pins = [Pin(keypad_columns[x], Pin.IN, Pin.PULL_DOWN) for x in range(4)]
row_pins = [Pin(keypad_rows[x], Pin.OUT) for x in range(4)]
for row_pin in row_pins:
    row_pin.value(1)

guess = []
secret_pin = ['1', '2', '3', '4', '5', '6']


def setup():
    lcd.move_to(0, 0)
    lcd.putstr("Enter a Key :-")
    utime.sleep(0.5)
    lcd.clear()

def scankeys():
    for row in range(4):
        row_pins[row].high()
        for col in range(4):
            if col_pins[col].value() == 1:
                key_press = matrix_keys[row][col]
                print("You have pressed:", key_press)
                lcd.clear()
                lcd.move_to(0, 0)
                lcd.putstr(f"Key: {key_press}")
                utime.sleep(0.3)
                lcd.clear()
                guess.append(key_press)
                if len(guess) == 6:
                    checkPin(guess)
                    guess.clear()
        row_pins[row].low()

def checkPin(guess):            
    if guess == secret_pin:
        print("You got the secret pin correct")
        lcd.putstr("Door unlock")
        for position in range(4500, 9000, 50):
            pwm.duty_u16(position)
            utime.sleep(0.05)
        for position in range(9000, 4500, -50):
            pwm.duty_u16(position)
            utime.sleep(0.05)
    else:
        print("pin is wrong")
        lcd.putstr("incorrect pin")
        led.value(1)
        utime.sleep(5)
        led.value(0)

print("Enter the secret Pin") 
setup()
while True:
    scankeys()
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT