from machine import Pin  # Importing the Pin module from the machine library for controlling GPIO pins
import utime  # Importing utime for adding delays

# Keypad matrix layout with corresponding characters
matrix_keys = [['1', '2', '3', 'A'],
               ['4', '5', '6', 'B'],
               ['7', '8', '9', 'C'],
               ['*', '0', '#', 'D']]

# Defining row and column pin numbers for the keypad
keypad_rows = [9, 8, 7, 6]
keypad_columns = [5, 4, 3, 2]

# Lists to store Pin objects for rows and columns
col_pins = []
row_pins = []

# Storing the user's keypresses and setting the secret PIN
guess = []
secret_pin = ['8', '1', '2', '0', '0', '5']

# Defining the LED pin (GPIO 15) as an output with a pull-up resistor
led = Pin(15, Pin.OUT, Pin.PULL_UP)

# Setting up each row pin as output and initializing to high, and each column pin as input with pull-down
for x in range(0, 4):
    row_pins.append(Pin(keypad_rows[x], Pin.OUT))
    row_pins[x].value(1)
    col_pins.append(Pin(keypad_columns[x], Pin.IN, Pin.PULL_DOWN))

# Function to scan the keypad for pressed keys
def scankeys():
    for row in range(4):
        row_pins[row].high()  # Activate the current row
        for col in range(4):
            if col_pins[col].value() == 1:  # Check if any column is active
                utime.sleep(0.02)  # Debounce delay
                if col_pins[col].value() == 1:  # Confirm key press after debouncing
                    print("You have pressed:", matrix_keys[row][col])
                    key_press = matrix_keys[row][col]
                    guess.append(key_press)  # Add pressed key to the guess list
                    utime.sleep(0.3)  # Small delay between presses
                    if len(guess) == 6:  # If the guess has 6 characters, check the PIN
                        checkPin(guess)
                        guess.clear()  # Clear the guess list after checking
        row_pins[row].low()  # Deactivate the current row

# Function to check if the entered PIN matches the secret PIN
def checkPin(guess):
    if guess == secret_pin:  # If the PIN is correct
        print("Access granted!")
        led.value(1)  # Turn on the LED for 3 seconds
        utime.sleep(3)
        led.value(0)  # Turn off the LED
    else:
        print("Access denied! Please enter correct password.")  # If the PIN is incorrect

print("Enter the secret Pin")  # Initial prompt for the user

# Infinite loop to continuously scan for key presses
while True:
    scankeys()
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT