If a large number of keys have to be scanned, the individual keys are not normally connected directly to the microcontroller. Instead, a matrix arrangement is used. This allows the number of port pins to be reduced to seven for twelve keys, for example. The software scans the rows and columns and thus determines which key is pressed. However, sometimes only a small microcontroller with just a few port pins is available, so even this economical matrix method cannot be used.
Using a trick, the same problem can be solved using only four port pins. This requires the use of four extra diodes and the possibility of individually configuring the pins as either inputs or outputs via software. Four column lines (1- 4) are arranged in a matrix with the four-row lines (A-D) that are connected to the microcontroller, with each row line connected to a column line by a diode (1N4148).
The software can recognize a pressed a key by applying a voltage to each row in turn while observing the states of the remaining port pins, which are configured as inputs. Thanks to the diodes, a voltage will be detected on only one of the inputs, depending on which key is pressed, and the software can assign the appropriate action to this event.