by Professor Petabyte
Keypads are essentially small numeric keyboards, which are mostly used as combination locks. The two common varieties are 12 and 16 key KeyPads.
For this demonstration GPIO pins 0 - 7 are used. Other GPIO pins can be used. Starting from the left of the, the connections on the ribbon cable are
Note that normal jumper wires can be plugged straight into the ribbon cable connector.
from machine import Pin import time # Define the key labels keypad = [ ['1', '2', '3', 'A'], ['4', '5', '6', 'B'], ['7', '8', '9', 'C'], ['*', '0', '#', 'D'] ] # Initialize GPIO pins for rows (outputs) row_pins = [Pin(i, Pin.OUT) for i in range(4)] # GPIO 0 to 3 # Initialize GPIO pins for columns (inputs with pull-down) col_pins = [Pin(i + 4, Pin.IN, Pin.PULL_DOWN) for i in range(4)] # GPIO 4 to 7 def scan_keypad(): for row_index, row in enumerate(row_pins): # Set all rows low for r in row_pins: r.value(0) # Set current row high row.value(1) # Check each column for col_index, col in enumerate(col_pins): if col.value() == 1: return keypad[row_index][col_index] return None # Main loop print("Keypad ready. Press a key:") while True: key = scan_keypad() if key: print("Key pressed:", key) # Wait for key release (debounce) while scan_keypad() == key: time.sleep(0.05) time.sleep(0.1)