Key Scan

The scan_keys() function starts by recording which of the columns contains the pressed button. Each column is assigned a value which is stored in the key_pressed variable as shown in the figure below. When the column has been recorded, the row and column pins are inverted in the sense that the rows become inputs and the columns become outputs.

Figure 1. Key Scan Function Overview

The key_pressed variable is incremented by a value depending on which row is detected to contain the pushed button. If, for example, button B is pressed, COLUMN 3 would be recorded first, with a value of 3 being stored into the key_pressed variable. Then ROW 1 would be recorded, which would add 4 to the variable, giving the variable a total of 7. Counting the buttons of the keypad left to right and top to bottom, button B (with a zero-indexed numbering scheme) is button number 7.

After recording the button press, the pins are reset to the initial state with columns as inputs and rows as outputs.