Chapter 22 Matrix Keypad
Earlier we learned about a single push button switch. In this chapter, we will learn about matrix keyboards, which integrates a number of push button switches as keys for the purposes of input.
Project 22.1 Matrix Keypad
In this project, we will attempt to get every key code on the matrix keypad to work.
Component List
ESP32-WROVER x1
|
GPIO Extension Board x1
|
Breadboard x1
|
|
4x4 Matrix Keypad x1
|
Jumper M/M x8 |
Component knowledge
4x4 Matrix Keypad
A keypad matrix is a device that integrates a number of keys in one package. As is shown below, a 4x4 keypad matrix integrates 16 keys:
Similar to the integration of a LED matrix, the 4x4 keypad matrix has each row of keys connected with one pin and this is the same for the columns. Such efficient connections reduce the number of processor ports required. The internal circuit of the Keypad Matrix is shown below.
The usage is similar to the LED matrix, using a row or column scanning method to detect the state of each key’s position by column and row. Take column scanning method as an example, send low level to the first 1 column (Pin1), detect level state of row 5, 6, 7, 8 to judge whether the key A, B, C, D are pressed. Then send low level to column 2, 3, 4 in turn to detect whether other keys are pressed. Therefore, you can get the state of all of the keys.
Circuit
Schematic diagram |
|
Hardware connection |
If you need any support, please feel free to contact us via: support@freenove.com
|
Sketch
This code is used to obtain all key codes of the 4x4 matrix keypad, when one of the keys is pressed, the key code will be printed out via serial port.
How to install the library
We use the third party library Keypad. If you haven’t installed it yet, please do so before learning.
The steps to add third-party Libraries are as follows: open arduino -> Sketch -> Include library -> Manage libraries. Enter “ Keypad” in the search bar and select “Keypad” for installation.
Refer to the following operations:
Sketch_22.1_Get_Input_Characters
Download the code to ESP32-WROVER, open the serial port monitor, set the baud rate to 115200, press the keyboard, the value of the pressed keys will be printed out via the serial port. As shown in the following figure:
The following is the program code:
1/**********************************************************************
2 Filename : Get Input Characters
3 Description : Call the Keypad function to set the matrix keyboard and get the value for the matrix keyboard
4 Auther : www.freenove.com
5 Modification: 2024/06/19
6**********************************************************************/
7#include <Keypad.h>
8
9// define the symbols on the buttons of the keypad
10char keys[4][4] = {
11 {'1', '2', '3', 'A'},
12 {'4', '5', '6', 'B'},
13 {'7', '8', '9', 'C'},
14 {'*', '0', '#', 'D'}
15};
16
17byte rowPins[4] = {14, 27, 26, 25}; // connect to the row pinouts of the keypad
18byte colPins[4] = {13, 21, 22, 23}; // connect to the column pinouts of the keypad
19
20// initialize an instance of class NewKeypad
21Keypad myKeypad = Keypad(makeKeymap(keys), rowPins, colPins, 4, 4);
22
23void setup() {
24 Serial.begin(115200); // Initialize the serial port and set the baud rate to 115200
25 Serial.println("ESP32 is ready!"); // Print the string "UNO is ready!"
26}
27
28void loop() {
29 // Get the character input
30 char keyPressed = myKeypad.getKey();
31 // If there is a character input, sent it to the serial port
32 if (keyPressed) {
33 Serial.println(keyPressed);
34 }
35}
First, add header file, define 4*4 matrix keyboard key value and the matrix keyboard pin.
1#include <Keypad.h>
2
3// define the symbols on the buttons of the keypad
4char keys[4][4] = {
5 {'1', '2', '3', 'A'},
6 {'4', '5', '6', 'B'},
7 {'7', '8', '9', 'C'},
8 {'*', '0', '#', 'D'}
9};
10
11byte rowPins[4] = {14, 27, 26, 25}; // connect to the row pinouts of the keypad
12byte colPins[4] = {13, 21, 22, 23}; // connect to the column pinouts of the keypad
Second, define a matrix keyboard object and associate the keys and pins with it.
1Keypad myKeypad = Keypad(makeKeymap(keys), rowPins, colPins, 4, 4);
Finally, get the key value and print it out via the serial port.
1void loop() {
2 // Get the character input
3 char keyPressed = myKeypad.getKey();
4 // If there is a character input, sent it to the serial port
5 if (keyPressed) {
6 Serial.println(keyPressed);
7 }
8}
Reference
You need to add the library each time you use the Keypad.
- class Keypad
Keypad(char *userKeymap, byte *row, byte *col, byte numRows, byte numCols);
Constructor, the parameters are: key code of keyboard, row pin, column pin, the number of rows, the number of columns.
char getKey();
Get the key code of the pressed key. If no key is pressed, the return value is NULL.
void setDebounceTime(uint);
Set the debounce time with a default time of 10ms.
void setHoldTime(uint);
Set the duration for the key to keep stable state after pressed.
bool isPressed(char keyChar);
Judge whether the key with code “keyChar” is pressed.
char waitForKey();
Wait for a key to be pressed, and return key code of the pressed key.
KeyState getState();
Get the state of the keys.
bool keyStateChanged();
Judge whether there is a change of key state, then return True or False.
For More information about Keypad, please visit: http://playground.arduino.cc/Code/Keypad
Project 22.2 Keypad Door
In this project, we use keypad as a keyboard to control the action of the servo motor.
Component List
ESP32-WROVER x1
|
GPIO Extension Board x1
|
|
Breadboard x1
|
||
Jumper M/M
|
Servo x1 |
4x4 Matrix Keypad x1 |
NPN transistorx1 (S8050)
|
Active buzzer x1 |
Resistor 1kΩ x1 |
Circuit
Schematic diagram |
|
Hardware connection |
If you need any support, please feel free to contact us via: support@freenove.com
|
Sketch
Sketch_22.2_Keypad_Door
Verify and upload the code to the ESP32-WROVER and press the keypad to input password with 4 characters. If the input is correct, the servo will move to a certain degree, then return to the original position. If the input is wrong, an input error alarm will be generated.
The following is the program code:
1/**********************************************************************
2 Filename : Combination Lock
3 Description : Make a simple combination lock.
4 Auther : www.freenove.com
5 Modification: 2024/06/19
6**********************************************************************/
7#include <Keypad.h>
8#include <ESP32Servo.h>
9
10// define the symbols on the buttons of the keypad
11char keys[4][4] = {
12 {'1', '2', '3', 'A'},
13 {'4', '5', '6', 'B'},
14 {'7', '8', '9', 'C'},
15 {'*', '0', '#', 'D'}
16};
17
18byte rowPins[4] = {14, 27, 26, 25}; // connect to the row pinouts of the keypad
19byte colPins[4] = {13, 21, 22, 23}; // connect to the column pinouts of the keypad
20
21// initialize an instance of class NewKeypad
22Keypad myKeypad = Keypad(makeKeymap(keys), rowPins, colPins, 4, 4);
23
24Servo myservo; // Create servo object to control a servo
25int servoPin = 19; // Define the servo pin
26int buzzerPin = 18; // Define the buzzer pin
27
28char passWord[] = {"1234"}; // Save the correct password
29
30void setup() {
31 myservo.setPeriodHertz(50); // standard 50 hz servo
32 myservo.attach(servoPin, 500, 2500); // attaches the servo on servoPin to the servo object
33 // set the high level time range of the servo motor for an accurate 0 to 180 sweep
34 myservo.write(0); // Set the starting position of the servo motor
35 pinMode(buzzerPin, OUTPUT);
36 Serial.begin(115200);
37}
38
39void loop() {
40 static char keyIn[4]; // Save the input character
41 static byte keyInNum = 0; // Save the the number of input characters
42 char keyPressed = myKeypad.getKey(); // Get the character input
43 // Handle the input characters
44 if (keyPressed) {
45 // Make a prompt tone each time press the key
46 digitalWrite(buzzerPin, HIGH);
47 delay(100);
48 digitalWrite(buzzerPin, LOW);
49 // Save the input characters
50 keyIn[keyInNum++] = keyPressed;
51 // Judge the correctness after input
52 if (keyInNum == 4) {
53 bool isRight = true; // Save password is correct or not
54 for (int i = 0; i < 4; i++) { // Judge each character of the password is correct or not
55 if (keyIn[i] != passWord[i])
56 isRight = false; // Mark wrong passageword if there is any wrong character.
57 }
58 if (isRight) { // If the input password is right
59 myservo.write(90); // Open the switch
60 delay(2000); // Delay a period of time
61 myservo.write(0); // Close the switch
62 Serial.println("passWord right!");
63 }
64 else { // If the input password is wrong
65 digitalWrite(buzzerPin, HIGH);// Make a wrong password prompt tone
66 delay(1000);
67 digitalWrite(buzzerPin, LOW);
68 Serial.println("passWord error!");
69 }
70 keyInNum = 0; // Reset the number of the input characters to 0
71 }
72 }
73}
First, we need to set the value of the password.
1char passWord[] = {"1234"}; // Save the correct password
Second, each time the key is pressed, the buzzer makes a short sound and stores the key value entered.
1char keyPressed = myKeypad.getKey(); // Get the character input
2// Handle the input characters
3if (keyPressed) {
4 // Make a prompt tone each time press the key
5 digitalWrite(buzzerPin, HIGH);
6 delay(100);
7 digitalWrite(buzzerPin, LOW);
8 // Save the input characters
9 keyIn[keyInNum++] = keyPressed;
Third, if the button has been pressed for four times, ESP32 begins to judge if the password is correct.
1if (keyInNum == 4) {
2 bool isRight = true; // Save password is correct or not
3 for (int i = 0; i < 4; i++) { // Judge each character of the password is correct or not
4 if (keyIn[i] != passWord[i])
5 isRight = false; // Mark wrong passageword if there is any wrong character.
6 }
If the password is correct, control the servo motor to open the lock and wait for 2 seconds before closing the lock. If it is not correct, the buzzer makes a long sound and prints the error message through the serial port.
1if (isRight) { // If the input password is right
2 myservo.write(90); // Open the switch
3 delay(2000); // Delay a period of time
4 myservo.write(0); // Close the switch
5 Serial.println("passWord right!");
6}
7else { // If the input password is wrong
8 digitalWrite(buzzerPin, HIGH);// Make a wrong password prompt tone
9 delay(1000);
10 digitalWrite(buzzerPin, LOW);
11 Serial.println("passWord error!");
12}
Finally, remember to empty the keyInNum every time.
1keyInNum = 0; // Reset the number of the input characters to 0
For More information about Keypad, please visit: http://playground.arduino.cc/Code/Keypad .












