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+

Elite Explorer Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

Arduino Uno R4 WiFi

-

Jumper Wires

BUY

Keypad

BUY

Wiring

../_images/21-keypad_bb.png

Schematic Diagram

../_images/21_keypad_schematic.png

Code

Note

  • You can open the file 21-keypad.ino under the path of elite-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

  1. 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.

  2. 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 and COLS constants define the dimensions of the keypad.

    • keys is a 2D array storing the label for each button on the keypad.

    • rowPins and colPins are arrays that store the Arduino pins connected to the keypad rows and columns.


  3. Initialize Keypad

    Create an instance of Adafruit_Keypad called myKeypad and initialize it.

    Adafruit_Keypad myKeypad = Adafruit_Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
    
  4. setup() Function

    Initialize Serial communication and the custom keypad.

    void setup() {
      Serial.begin(9600);
      myKeypad.begin();
    }
    
  5. 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);
    }