Pico Projects

←Index

Using KeyPads

by Professor Petabyte

 

Zoomable Image
Mouseover to Zoom

What are KeyPads

Keypads are essentially small numeric keyboards, which are mostly used as combination locks. The two common varieties are 12 and 16 key KeyPads.

Keypad Wiring

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.

The Micropython Code

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)
Zoomable Image
Mouseover to Zoom

Important Points

  1. Ensure you connect the rows to GPIO 0 - 3 and columns to GPIO 4 - 7.
  2. Use external pull-down resistors (10kΩ) on column lines if input floating issues occur, though Pin.PULL_DOWN usually suffices.
  3. If keys don't register reliably, increase debounce delay (time.sleep(0.05)) fron 0.05 to 0.1. If this is necessary, try increasing the delay incrementally, e.g. 0.01 at a time, until satisfactory operation is achieved.




© 2025 Professor Petabyte