Keypad¶
Overview¶
In this lesson, you will learn to use Keypad. Keypad can be applied into various kinds of devices, including mobile phone, fax machine, microwave oven and so on. It is commonly used in user input.
Required Components¶
In this project, we need the following components.
It’s definitely convenient to buy a whole kit, here’s the link:
Name |
ITEMS IN THIS KIT |
LINK |
---|---|---|
Elite Explorer Kit |
300+ |
You can also buy them separately from the links below.
COMPONENT INTRODUCTION |
PURCHASE LINK |
---|---|
- |
|
Wiring¶
Schematic Diagram¶
Code¶
Note
You can open the file
21-keypad.ino
under the path ofelite-explorer-kit-main\basic_project\21-keypad
directly.To install the library, use the Arduino Library Manager and search for “Adafruit Keypad” and install it.
After uploading the codes to the UNO board, on the serial monitor, you can see the value of the key currently pressed on the Keypad.
Code Analysis¶
Including the Library
We start by including the
Adafruit_Keypad
library, which allows us to easily interface with the keypad.#include "Adafruit_Keypad.h"
Note
To install the library, use the Arduino Library Manager and search for “Adafruit Keypad” and install it.
Keypad Configuration
const byte ROWS = 4; const byte COLS = 4; char keys[ROWS][COLS] = { { '1', '2', '3', 'A' }, { '4', '5', '6', 'B' }, { '7', '8', '9', 'C' }, { '*', '0', '#', 'D' } }; byte rowPins[ROWS] = { 2, 3, 4, 5 }; byte colPins[COLS] = { 8, 9, 10, 11 };
The
ROWS
andCOLS
constants define the dimensions of the keypad.keys
is a 2D array storing the label for each button on the keypad.rowPins
andcolPins
are arrays that store the Arduino pins connected to the keypad rows and columns.
Initialize Keypad
Create an instance of
Adafruit_Keypad
calledmyKeypad
and initialize it.Adafruit_Keypad myKeypad = Adafruit_Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
setup() Function
Initialize Serial communication and the custom keypad.
void setup() { Serial.begin(9600); myKeypad.begin(); }
Main Loop
Check for key events and display them in the Serial Monitor.
void loop() { myKeypad.tick(); while (myKeypad.available()) { keypadEvent e = myKeypad.read(); Serial.print((char)e.bit.KEY); if (e.bit.EVENT == KEY_JUST_PRESSED) Serial.println(" pressed"); else if (e.bit.EVENT == KEY_JUST_RELEASED) Serial.println(" released"); } delay(10); }