# Using a 4×4 Digital Keypad with Arduino

3.4
(5)

Whether it’s a calculator or the keypad of a building, we commonly use numeric keypads. The 4×4 numeric keypad is a matrix of 16 buttons whose states can be detected by a microcontroller.

## Hardware

• Computer
• Arduino UNO
• USB cable A Male to B Male

## Principle of operation

Numerical keypad is a set of 16 buttons that are arranged in a matrix, i.e. all the buttons in a column are linked to one input and all the buttons in a row are linked to another. When a button is pressed, the input corresponding to the line is connected to the input corresponding to the column, which closes the circuit. The advantage of this type of assembly is that 16 buttons can be managed with only 8 microcontroller inputs.

## Scematic

The numeric keypad uses 8 pins of the Arduino. It is possible to connect them to any pin. Pins 0 and 1, which are used for serial connection via the USB port, should be avoided.

## Code

To manage the numerical keypad, the principle is to switch each entry in the columns to the high state and to read the value of the entries corresponding to the lines. If a line is in the same state as the column, a button is pressed. In practice we can use the Keypad.h library, which allows us to manage a matrix of buttons of any size.

```//Libraries

//Constants
#define ROWS 4
#define COLS 4

//Parameters
const char kp4x4Keys[ROWS][COLS]  = {{'1', '2', '3', 'A'}, {'4', '5', '6', 'B'}, {'7', '8', '9', 'C'}, {'*', '0', '#', 'D'}};
byte rowKp4x4Pin [4] = {9, 8, 7, 6};
byte colKp4x4Pin [4] = {5, 4, 3, 2};

//Variables

void setup() {
//Init Serial USB
Serial.begin(9600);
Serial.println(F("Initialize System"));
}

void loop() {
}

char customKey = kp4x4.getKey();
if (customKey) {
Serial.println(customKey);
}
}

﻿

```

## Result

When a key on the keyboard is pressed, we observe that the associated character is correctly displayed in the serial monitor.

## Applications

• Create an interface with several buttons
• Creating a lock operated by a code reader
• Develop an alarm that can be activated or deactivated by means of a password.

## Sources

Find other examples and tutorials in our Automatic code generator