from machine import Pin,I2C
from time import sleep
from esp32_i2c_lcd import I2cLcd 
lcdI2C=I2C(scl=Pin(22),sda=Pin(21),freq=100000)
lcd=I2cLcd(lcdI2C,0x27,2,16)


rowPin =[Pin(26,Pin.OUT),Pin(27,Pin.OUT),Pin(19,Pin.OUT),Pin(18,Pin.OUT)]
colPin=[Pin(5,Pin.IN,Pin.PULL_DOWN),Pin(4,Pin.IN,Pin.PULL_DOWN),Pin(2,Pin.IN,Pin.PULL_DOWN),Pin(15,Pin.IN,Pin.PULL_DOWN)]

def key():
    sw=[(1,2,3,4),
        (5,6,7,8),
        (9,10,11,12),
        (13,14,15,16)]


    for r in range(4):
        for row in rowPin:
            row.value(0)
        rowPin[r].value(1)
        for c in range(4):
            if colPin[c].value()==1:
                return sw[r][c]
    return -1

lcd.putstr("Password:")
pw="1111"
pw_i=""

while True:
    pad=key()
    if pad >=0:
        pw_i += str(pad)
        lcd.clear()
        lcd.putstr("Password :"+pw_i)
        if len(pw_i)==4:
            if pw_i==pw:
                lcd.clear()
                lcd.putstr("pw is correct.")
                lcd.move_to(3,1)
                lcd.putstr("GOOD  LUCK")
                break
            else:
                lcd.clear()
                lcd.putstr("pw is incorrect.")
                lcd.putstr("please try again")
                sleep(3)
    
            pw_i=""
            lcd.clear()
            lcd.putstr("password :")
            sleep(1)