Now lets talk about the different approaches of keypad scanning, which is required to identify which key has been pressed.
Sequential exploration of rows: In this method, the I/O pins connecting the rows are all configured as output and those connecting the columns are defined as input, or vice-versa. The column lines, which are inputs to the microcontroller, are pulled-high using the internal pull-up resistors. Therefore, the default input to these lines is 1. The state for the matrix keypad can be explored by turning the rows low sequentially, one at a time, and reading the columns. For example, set the first row to 0 and read all the columns. If any key has been pressed in that row, the corresponding column line must read as 0. Otherwise, go to the next row and set it to 0, and read the columns again. This process is repeated until a 0 is found in a column. This determines the row and column for the pressed key, thus giving the exploration code for that key.
Simultaneous exploration of rows and columns: In this method, all rows and columns are explored simultaneously in two phases. First, the rows are configured as output and the columns as input. Internal pull-ups are enabled on the column lines. Then all rows are set to 0 and the columns are read. In any key has been pressed, the corresponding column will be read as 0. This detects the column but not its row. The whole process is reversed next. The rows are configured as input and the columns as output. Internal weak pull-ups are now enabled on row lines. All columns are set to 0, and the rows are read. The row that reads 0 contains the pressed key. This gives both the row and column for the pressed key. This approach of exploring the keypad is relatively faster than sequential exploration approach.
In case the microcontroller does not have the internal pull-up feature on its I/O port, the pull-up resistors on the input lines must be connected externally.Software
I wrote the keypad scanning subroutine in mikroC Pro for PIC compiler, for both the techniques described in the theory section. In order to enable the weak pull-up on PORTB pins, the Weak Pull-up Enable (WPUEN) bit of OPTION_REG must be cleared and the corresponding bits of Weak Pull-Up on PORTB (WPUB) register must be set. The two programs (source code and HEX files) can be downloaded from the links provided below. Note that the mikroC Pro for PIC compiler also provides built-in library for Matrix Keypad, but that is not used here.