4x4 Matrix Keypad
Module Source
Specifications
Hardware Interface
The 4x4 matrix keypad has 8 pins, corresponding to 4 rows and 4 columns. You need to connect each pin to a digital pin on the Arduino.
- Connect the 4 row pins of the keypad to 4 digital pins on the Arduino, such as pins 2, 3, 4, and 5.
- Connect the 4 column pins of the keypad to another 4 digital pins on the Arduino, such as pins 6, 7, 8, and 9.
Usage Method
Install the Library
Arduino does not have a standard library to read data from a matrix keypad, but there is a commonly used third-party library called Keypad
that can handle this task. In the Arduino IDE, you can search for and install the Keypad
library via the "Library Manager."
Enter the code:
c
/******************************************************************************
* Test Hardware: LCSC ColorEasyDuino Development Board
* Version Number: V1.0
* Modified By: www.lckfb.com
* Modification Date: April 11, 2024
* Function Overview:
*****************************************************************************
* Open-source development board hardware and software information and related projects hardware and software information on official website
* Development board official website: www.lckfb.com
* Technical support resident forum, any technical problems are welcome at any time to exchange learning
* LCSC Forum: club.szlcsc.com
* Follow our Bilibili account: [立创开发板], stay toned to our latest news!
* We focus on cultivating Chinese engineers rather than profiting from board sales.
******************************************************************************/
#include <Keypad.h>
// 定义键盘尺寸
const byte ROWS = 4; // 四行
const byte COLS = 4; // 四列
// 定义连接到行和列的Arduino引脚
byte rowPins[] = {2, 3, 4, 5};
byte colPins[] = {6, 7, 8, 9};
// 定义每个按键代表的字符
char keys[][] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
// 创建Keypad对象
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
void setup() {
Serial.begin(9600);
}
void loop() {
char key = keypad.getKey();
// 检查是否有按键被按下
if (key) {
// 输出按键
Serial.println(key);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
Usage Testing
When you press a corresponding key, the serial monitor will output the number of the key that was pressed. If the number is incorrect, it may be due to the rows and columns being connected in reverse.