Site icon AranaCorp

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

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
#include <Keypad.h>//https://github.com/Chris--A/Keypad

//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
Keypad kp4x4  = Keypad(makeKeymap(kp4x4Keys), rowKp4x4Pin, colKp4x4Pin, ROWS, COLS);

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

void loop() {
  readKp4x4();
}

void readKp4x4() { /* function readKp4x4 */
  //// Read button states from keypad
  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

Sources

Find other examples and tutorials in our Automatic code generator
Code Architect

How useful was this post?

Click on a star to rate it!

Average rating 3.4 / 5. Vote count: 5

No votes so far! Be the first to rate this post.

Exit mobile version