16-key Keypad Tutorial

These 16-pin keypads are all over the place, and interfacing to them keeps getting easier. Today there is an Arduino library that takes care of it for you. Just include it, map out your keys, and go.

The way keys are scanned is by sending a strobe down one line and reading the returns one at a time looking for any shorts caused by a pressed key. To scan one of these 16-key keypads you need four strobe lines and four returns. If you add one more key, you will either have to add a strobe line or a return. Then you can add a total of four more keys. A four x eight keypad would require 12 lines. There is a point where the Arduino just doesn't have enough pins, and a different kind of keypad is required.

The code

The first line includes the library header file, so we can call the keypad code when we need. Then we define the number of rows and columns. The next part, the key_matrix, describes which key is which. The library needs that in order to translate the row and column into a character. We could call the key at (0,0) question mark "?", and that's what the keypad library would return when you pressed the "1" key.

The next few lines show the keypad library which pins to use. Be sure to use pins that are not being used by other things. The original example code for this library used pins D0 - D7. D0 and D1 are used by the serial port. You can't also use them as keypad lines! I changed it to use pins D2 - D9.

Then we make a keypad object. It needs to know all of the things we defined earlier, like the row count, column count, key matrix, and pins. It initializes the keypad logic.

The remaining code looks for keys and acts on them. If no key is pressed, nothing happens, but if a key is pressed, it is sent back to the serial monitor.


#include <Keypad.h>

#define ROWS 4
#define COLS 4

char key_matrix[COLS][ROWS] = {
  {'1','4','7','*'},
  {'2','5','8','0'},
  {'3','6','9','#'},
  {'A','B','C','D'}
};

// Set up the pins used for scanning.
// Don't use 0 or 1 (serial port)
uint8_t row_pins[ROWS] = {5, 4, 3, 2};
uint8_t col_pins[COLS] = {9, 8, 7, 6};

// Instantiate a Keypad object.
Keypad keypad = Keypad( makeKeymap(key_matrix), row_pins, col_pins, ROWS, COLS); 

void setup()
{
  Serial.begin(9600);
}
  
void loop()
{
  char key_pressed;
  
  if ((key_pressed = keypad.getKey()) != false)
  {
    Serial.println(key_pressed);
  }
}
    

The keypad is connected to the Uno using a male-male 8-conductor ribbon cable. Other means of connecting the keypad are not really too practical, since the keypad has a single row 8-pin header socket, and the pins we need are spread across two ports.

Arduino Board Logo

 

Arduino-Board is the go-to source for information on many available Arduino and Arduino-like boards, tutorials and projects.

Help and Support

Arduino-Board

Stay updated

Sign up if you would like to receive our once monthly newsletter.