from time import ticks_ms, ticks_diff
from machine import Pin

import time
from servo import Servo
my_servo = Servo(pin_id=27)
my_servo.write(30)


class Key:
    def __init__(self, name):
        self.name = name
        self.active = False

row_pins = []
col_pins = []

keys = [
    [Key('1'), Key('2'), Key('3'), Key('A')],
    [Key('4'), Key('5'), Key('6'), Key('B')],
    [Key('7'), Key('8'), Key('9'), Key('C')],
    [Key('*'), Key('0'), Key('#'), Key('D')]
]

for pin_num in range(15, 11, -1):
    row_pins.append(Pin(pin_num, Pin.OUT))

for pin_num in range(11, 7, -1):
    col_pins.append(Pin(pin_num, Pin.IN, Pin.PULL_DOWN))

# Define the LED pin (assuming it's pin number 2 for this example, change as needed)
led = Pin(26, Pin.OUT)

# A variable to keep track of when the LED was turned on
led_turned_on_at = None
led_on_duration = 5000  # LED should be on for 5000ms = 5 seconds

def scan_keys():
    for row, row_pin in enumerate(row_pins):
        row_pin.on()

        for col, col_pin in enumerate(col_pins):
            keys[row][col].active = bool(col_pin.value())

        row_pin.off()

entered_password = ''

correct_password = '2023'

while True:
    scan_keys()

    for row in keys:
        for key in row:
            if key.active:
                if key.name == '#':
                    print()
                    if entered_password == correct_password:
                        print("Welcome in!")
                        led.on()
                        led_turned_on_at = ticks_ms()
                        unlock()
                    else:
                        print("Wrong Password")
                    entered_password = ''
                else:
                    print(key.name, end='')
                    entered_password += key.name
                # debounce
                while key.active:
                    scan_keys()

    # Check if the LED should be turned off
    if led_turned_on_at is not None:
        elapsed_time = ticks_diff(ticks_ms(), led_turned_on_at)
        if elapsed_time > led_on_duration:
            led.off()
            led_turned_on_at = None
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT