Full working sourcecode is here

Using a matrix keypad

The matrix keypad is wired internally in rows and columns. When a button is pressed it connects a row to a column. A microcontroller interfaced to such a keypad must “scan” the keypad by activating each of the rows (or columns) in turn and then checking to see which of the columns (or rows) indicates that a button has been pressed. This scanning is done in software by driving port pins high (or low). The interface strategy here is to configure all pins that are attached to the keypad as inputs with internal pull-up resistors enabled. The result is that all pins float to logic 1 when no buttons are pressed. To scan a kaypad row the pin connected to the row is driven low. The processor then checks to see if any of the columns are low. If a low is detechted on a column then the conclusion is that the button that connects that row to that column was pressed. This process is repeated for each of the rows.