Coursify

Microprocessor

Keyboard Interfacing

1.25 hours

Learning Goals

  • Understand matrix keyboard architecture: recognizing row/column matrix organization reducing pin requirements (4×4 matrix uses 8 pins instead of 16), understanding key identification through row/column intersection, and managing power consumption through pull-up/pull-down configurations
  • Master keyboard scanning techniques: implementing column-by-column scanning by sequentially activating columns and reading row ports, recognizing key closure when expected high becomes low through pull-down connection, and repeating scan at fixed intervals
  • Analyze debouncing requirements: understanding mechanical bouncing causing multiple transitions during key closure (typically 5-20 milliseconds), implementing software debouncing through repeated sampling within transition period, and recognizing timing constraints
  • Apply debouncing algorithms: implementing simple debouncing (sample twice within 20ms separated by delay), utilizing majority voting (sample 3-5 times and accept consensus), and managing debounce delay relative to scan rate
  • Master key identification logic: implementing two-dimensional lookup table indexed by row/column position, translating matrix positions to character codes (numerical pad, alphanumeric keyboard), and managing special keys (shift, control, enter)
  • Understand polling vs interrupt-driven approaches: polling continuously scanning keyboard in main loop (simple, predictable scan rate), interrupt-driven scanning on periodic timer interrupt (reduces polling overhead), and hybrid approaches
  • Apply interrupt-driven keyboard: implementing timer interrupt for regular scan initiation, buffering detected keys for main program processing, and managing scan rate relative to debounce timing requirements
  • Implement practical input handling: accepting numeric input for menu navigation, supporting string entry with backspace and clear, implementing single-key vs multiple simultaneous key detection, and managing keystroke queuing for rapid input

In embedded microprocessor systems, human-machine interaction frequently requires alphanumeric input. While interfacing individual tactile switches directly to microprocessor general-purpose input/output (GPIO) ports is viable for a small number of inputs, it becomes highly inefficient as the number of keys scales. For example, a 16-key keypad would demand 16 dedicated GPIO pins. To optimize hardware resources, microprocessors employ a Matrix Keyboard configuration .

By arranging keys at the intersections of a grid of row and column lines, a M×NM \times N matrix requires only M+NM + N physical microcontroller pins to interface with M×NM \times N switches . In a standard 4×44 \times 4 matrix layout, this architecture reduces the pin requirement from 16 to 8:

Pull-Up/Pull-Down Configurations and Electrical State Management

When no keys are pressed, the input lines are electrically disconnected (floating) from the output lines. To ensure a stable and predictable logic state, pull-up or pull-down resistors are integrated into the circuit.

  • Active-Low Configuration (Pull-up Resistors): Columns (configured as inputs) are tied to VCCV_{CC} via internal or external pull-up resistors . The rows (configured as outputs) are normally kept HIGH. During scanning, one row at a time is driven LOW (0 V0\text{ V}). If a key is pressed at the intersection of active Row ii and Column jj, the electrical contact pulls Column jj down to 0 V0\text{ V} (logic 0).
  • Active-High Configuration (Pull-down Resistors): Columns are tied to ground (GNDGND) via pull-down resistors . The active row is driven HIGH (VCCV_{CC}). If a key is pressed at the active intersection, the corresponding Column input goes HIGH (logic 1).

Footnotes

  1. Keyboard Interfacing with 8051 Microcontroller - Overview of matrix design, pin optimization, and active-low scan configurations. 2 3 4

Keyboard Interfacing with 8051 Microcontroller

Mechanical Key Bounce & Software Debouncing Algorithms

When a physical key is pressed, its metal contacts do not settle instantaneously. Instead, they make and break contact repeatedly for a brief period before achieving a steady state. This phenomenon, known as contact bounce , typically spans between 5 ms5\text{ ms} and 20 ms20\text{ ms}.

tbounce[5 ms,20 ms]t_{\text{bounce}} \in [5\text{ ms}, 20\text{ ms}]

Without mitigation, a microprocessor executing millions of instructions per second will interpret these transient oscillations as multiple, rapid, distinct key presses . Interfacing software must employ debouncing algorithms to ensure a single physical act produces exactly one registered input.

Voltage (V)
  ^
  |  +------+    +---+   +------- (Logical Press Complete)
  |  |      |    |   |   |
  |  |      |    |   |   |
  +--+      +----+   +---+
  |<-   t_bounce   ->|
  +-------------------------------------> Time (ms)

Software Debouncing Strategies

  1. Simple Double-Sampling with Delay: This algorithm reads the input state once. If a transition is detected (e.g., from logic HIGH to LOW), the software enters a non-blocking or blocking delay of 10 ms10\text{ ms} to 20 ms20\text{ ms}, allowing the contacts to settle. It then samples the input a second time. If the state matches the first sample, the keypress is validated .

  2. Majority Voting Filter (Consensus-Based): Instead of relying on a single delayed sample, the microprocessor samples the port state NN times (typically 33 to 55 times) over a fixed interval (e.g., every 5 ms5\text{ ms}). The validated state is determined by a majority vote:

    Statevalidated=1Ni=1NSi+0.5\text{State}_{\text{validated}} = \left\lfloor \frac{1}{N} \sum_{i=1}^{N} S_i + 0.5 \right\rfloor

    where Si{0,1}S_i \in \{0, 1\} represents the digital sample value. This technique filters out high-frequency electrical noise and transient glitches more effectively than simple delays.

Footnotes

  1. Software Debouncing Methods and Switch Bounce Characteristics - Analysis of mechanical switch bounce dynamics and software filtering. 2 3

Matrix Keyboard Scanning and Key Identification Algorithm

  1. 1
    Step 1

    Configure the row pins (e.g., Row 0 to Row 3) as digital outputs. Configure the column pins (e.g., Column 0 to Column 3) as digital inputs. Enable internal pull-up resistors on all column input pins so they default to logic HIGH (1).

  2. 2
    Step 2

    Drive all row output pins to logic LOW (0). Read the column input port. If all column inputs are HIGH (1111 in binary), no keys are currently pressed. Loop continuously until at least one column input reads LOW (0), indicating a keypress attempt.

  3. 3
    Step 3

    Once a column change is detected, wait for a debounce period (td20 mst_d \approx 20\text{ ms}) to bypass transient contact noise, or initiate a multi-sample majority voting check.

  4. 4
    Step 4

    Isolate the pressed key by scanning row-by-row. Drive Row 0 to LOW (0) and drive all other rows (Row 1, 2, 3) to HIGH (1). Read the column inputs. If any column is LOW, the pressed key lies on Row 0. If all columns are HIGH, proceed to drive Row 1 LOW (keeping others HIGH), and recheck. Repeat this sequence until a column reads LOW.

  5. 5
    Step 5

    When a active row ii and active column jj are identified, calculate the linear index: Index=(i×N)+j\text{Index} = (i \times N) + j Use this index to reference a two-dimensional translation lookup table (LUT) to retrieve the corresponding character (e.g., '0'-'9', 'A'-'F').

  6. 6
    Step 6

    To prevent continuous repeat triggers of the same keystroke, keep reading the column pins until they return to the default state (all 1s) before clearing the scan state and returning to step 2.

Critical Scan Rate Timing Constraints

The scan interval must be carefully calibrated. If the scan rate is too fast (e.g., <1 ms< 1\text{ ms}), the system may process mechanical bounces as independent keypresses despite basic checks. If the scan rate is too slow (e.g., >100 ms> 100\text{ ms}), the system will feel sluggish or miss rapid keystrokes entirely.

1#define ROWS 4 2#define COLS 4 3 4const char key_map[ROWS][COLS] = { 5 {'1', '2', '3', 'A'}, 6 {'4', '5', '6', 'B'}, 7 {'7', '8', '9', 'C'}, 8 {'*', '0', '#', 'D'} 9}; 10 11char scan_keypad() { 12 for (int r = 0; r < ROWS; r++) { 13 // Set all rows HIGH, then set current row LOW 14 set_all_rows_high(); 15 set_row_low(r); 16 17 // Small propagation delay 18 delay_us(5); 19 20 for (int c = 0; c < COLS; c++) { 21 if (read_column(c) == 0) { // Active Low detected 22 delay_ms(20); // Software Debounce 23 if (read_column(c) == 0) { 24 while (read_column(c) == 0); // Wait for key release 25 return key_map[r][c]; 26 } 27 } 28 } 29 } 30 return '\0'; // No key detected 31}

Power Consumption Optimization

In battery-powered devices, continuous polling of a matrix keyboard wastes significant CPU cycles and power. Use an external interrupt line combined with an OR gate connected to all column inputs. When any key is pressed, it triggers an asynchronous interrupt, waking the processor from deep-sleep mode to perform scanning .

Footnotes

  1. Interrupt-Driven Input Paradigms for Embedded Microprocessors - Architectural comparison between continuous polling, timer ISRs, and circular buffer queues.

Architecture: Polling vs. Interrupt-Driven Interfacing

Microprocessor systems process user inputs using either continuous checking or asynchronous event handling.

Interfacing TechniqueCPU OverheadLatencyDesign ComplexityOptimal Application Scenario
Polling MethodHigh (Continuous execution loop)Variable (Depends on loop execution time)Low (Simple state-machine code)Dedicated systems with minimal concurrent tasks (e.g., microwave controllers)
Interrupt-DrivenLow (Executes only on event trigger)Minimum (Immediate context switch)Medium to High (Requires interrupt service routines)Multitasking, real-time operating systems (RTOS)

Implementing a Hybrid Interrupt-Driven System

A highly robust keyboard interfacing structure combines timer-driven interrupts with a FIFO queue (circular buffer) .

  1. The Timer Interrupt: A hardware timer is configured to fire periodically (e.g., every 10 ms10\text{ ms}). This avoids blocking delays in the main application .
  2. The Interrupt Service Routine (ISR): At each timer tick, the ISR scans the matrix. It updates a state machine tracking whether a key is released, bouncing, or pressed.
  3. The Queue Buffer: Once the ISR confirms a stable new keypress, it writes the corresponding ASCII code into a software circular buffer. The main program reads from this buffer whenever it has idle clock cycles, preventing loss of keystrokes during intense computation .

Footnotes

  1. Interrupt-Driven Input Paradigms for Embedded Microprocessors - Architectural comparison between continuous polling, timer ISRs, and circular buffer queues. 2 3 4

Advanced Keyboard Interfacing Challenges & Solutions

Knowledge Check

Question 1 of 3
Q1Single choice

If a 5x5 matrix keyboard is used, how many microprocessor GPIO pins are saved compared to connecting every switch individually to a dedicated pin?

Keyboard Interfacing | Microprocessor | Coursify