Link here

Keypad Scan Uses Few I/O Lines
This simple electronic circuit efficiently scans and decodes a matrix of keypad buttons or input switches

A classic microcontroller design project involves decoding a matrix of keypad buttons. This application note provides an efficient method for scanning and decoding a large number of switches using few I/O lines. A technique known as Charlieplexing, involving clever use of diode switches while alternating I/O lines between output drive and input sensing, has been used for driving multiple LED segments efficiently1). A similar technique can be used to scan multiple switch closures using as few I/O lines as possible.

The more straightforward method uses N I/O lines to scan and decode a matrix of (N/2)2 keypad switches. Half of the lines are used for input and half are used for output. For example, row scan lines are set as inputs, and column lines are alternately driven as outputs. The new method uses all lines as both input and output. In this way N I/O lines are capable of detecting up to N2-N switch closures.

The basic idea is shown in the following figure:

Switches drive microcontroller's digital I/O pins

In this electronic circuit the two I/O pins are shown pulled up by resistors, although some microprocessor pins are internally pulled up. To read the state of S1, pin 2 is driven low and pin 1 is read. Conversely, to read the state of S2, pin 1 is driven low and pin 2 is read.

This circuit can be generalized to N I/O lines. Each I/O line requires one diode. Each I/O line is switched low in turn, and while it is low the other N-1 lines are read – a low indicating a switch closure. In this way, a 12-key numeric keypad can be read with only 4 I/O lines.

Figure 2 shows 4 I/O lines used to read a 12-key numeric keypad. Although the pull-up resistors are not shown, each I/O line requires one.

Efficiently scan matrix keypad - 12 key numeric keypad uses only four digital data inputs
Fig. 2  Efficiently scan a 12 key numeric keypad with only four of a microcontroller's digital input lines

The circuit can be expanded to accommodate additional switches. Adding another I/O pin adds the ability to read 8 more switches, still another adds another 10 switches, and so on. Eight I/O lines can read up to 56 switch closures.

See also → Digital I/O Wildcard Users Guide

See for example these Maxim and Microchip application notes
This page is about: Keypad Scan Uses Few I/O Lines, Decoding Keypad Buttons, Scan to Decode Matrix of Keypad Switches – A technique known as Charlieplexing, involving clever use of diodes and keypad switches while alternating I/O lines between output drive and input sensing, is used to efficiently decode an array of keypad switches detect switch closures, read matrix keypad, scan matrix keypad, keypad scan, scan keypad, detect button presses, few I/O lines detect many input switch closures, keypad state, switch state