Interfacing Matrix Keypad with PIC Microcontroller – XC8

a matrix keypad

Interfacing Matrix Keypad with PIC Microcontroller – XC8

Watch the Video Tutorial

Keypads are small keyboards that are used to enter numeric, alphanumeric or select configuration data to microcontroller systems. Keypads are available in a variety of sizes. The common sizes are 3×3, 4×3 and 4×4 keypads.

Keypads are widely used input devices with lots of application in our everyday life, devices like telephone, ATM, electronic lock, Calculator, timers just to name a few, all have some sort of a keypad.

A 3x4 Matrix Keypad

Figure 1: A 3×4 Matrix Keypad

A matrix keypad is basically a combination of push-buttons in a way to form rows and columns. In this way the number of input/output pins necessary for their connection to a microcontroller is reduced. A 4×3 keypad requires 7 input/output pins instead of 12 and a 4×4 will require 8 input/output pins instead of 16 pins. In the matrix keypad switches are connected in a special manner as shown in figure 2 below.

4x4 Matrix Keypad structure Figure 2: 4×4 Matrix Keypad structure         

The values of each key could be mapped according to ones specific project application. Figure 1, figure 3 and figure 4 show a typical keys mapping for a 3×4 and 4×4 Matrix keypads.

Keys mapping

Figure 3 Keys mapping with letters         Figure 4 Calculator Keys mapping

Detecting a pressed Key

A 3x4 Keypad connected to PORTB

                          Figure 5: A 3×4 Keypad connected to PORTB

Assuming that the keypad is connected to PORTB as shown on figure 5, the steps to determine which key is pressed are as follows:

  1. A logic 1 is applied to the first row via RB0 (Row A).
  2. Columns pins RB4–RB6 are read. If RB4 is 1, then it means key 1 is pressed, if RB5 is 1, key 2 is pressed and RB6 is 1, key 3 is pressed and if RB7 is 1, key + is pressed.
  3. A logic 1 is applied to the second row via RB1 (Row B).
  4. The columns of pins RB4–RB6 are read again. If RB4 is 1, key 4 is pressed, if RB5 is 1, key 5 and so on.
  5. The above process is repeated for all the four rows continuously.

XC8 Code

Let us create a simple project as shown on figure 5, it consists of a 3×4 keypad and a single digit 7-Segment display. the first key pressed on the keypad will be displayed on the 7-Segment display. A 1ms delay is used between each scan time to counter the effect on switch bouncing.

For more information on Switch bouncing, please visit the article Reading Switches with PIC Microcontroller.

A function called kbd_getc is used to get the first pressed key. This key is displayed on the 7-Segment display.

You can download the full project files (MPLAB XC8 source code and Proteus Schematic design) below here.

All the files are zipped, you will need to unzip them (Download a free version of the Winzip utility to unzip files).

Download: MPLAB_XC8_Project_Keypad

Download: Keypad_Proteus

Share this post

Select your currency