import machine
import utime
#Define the keypad matrix layout (4x4)
KEYPAD_ROWS = [machine.Pin(3), machine.Pin(2), machine.Pin(1), machine.Pin(0)]
KEYPAD_COLS = [machine.Pin(7), machine.Pin(6), machine.Pin(5), machine.Pin(4)]
#Keypad layout
keypad = [
['1' ,'2', '3', 'A'],
['4' ,'5' ,'6' ,'B'],
['7', '8', '9', 'C'],
['*' ,'0' ,'#' ,'D']
]
#Initialize the keypad pins
for row pin in KEYPAD_ROWS:
row_pin.init(mode=machine. Pin. IN, pull-machine.Pin.PULL_UP)
for col pin in KEYPAD COLS:
col_pin.init(mode=machine.Pin.OUT)
col_pin.value (1) #Set all column pins to high
#Function to scan the keypad and return the pressed key (if any)
def scan_keypad():
for col_num, col pin in enumerate (KEYPAD_COLS):
col pin.value(0) # Set the current column to low
for row_num, row pin in enumerate (KEYPAD_ROWS):
If not row_pin.value():
#Key pressed, wait for debouncing
utime.sleep_ms(50)
while not row_pin.value():
pass
# Return the pressed key
return keypad [row_num] [col_num]
col_pin.value(1) # Set the current column back to high
return None
# Main loop
while True:
key scan_keypad()
if key:
print("Key pressed;", key)