0% found this document useful (0 votes)
171 views20 pages

11 - Keypad Library

The document provides an overview of the Arduino Keypad library, which allows for reading matrix-style keypads without the need for external pull-up resistors. It includes installation instructions, example code for creating keypad instances, and explanations of various functions such as setting debounce and hold times, getting key values, and handling key events. Additionally, it poses exercises related to the library's functionality and implementation in Arduino programming.

Uploaded by

Sandiswa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
171 views20 pages

11 - Keypad Library

The document provides an overview of the Arduino Keypad library, which allows for reading matrix-style keypads without the need for external pull-up resistors. It includes installation instructions, example code for creating keypad instances, and explanations of various functions such as setting debounce and hold times, getting key values, and handling key events. Additionally, it poses exercises related to the library's functionality and implementation in Arduino programming.

Uploaded by

Sandiswa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Arduino

Arduino Uno ATmega328 Arduino Mega ATmega2560

Keypad library
Created by: Dr. Daniel van Niekerk
Introduction
̶ The Keypad library allows an Arduino to read a matrix style keypad.
̶ keypads come in 3x4, 4x4 and various other configurations with words, letters and
numbers written on the keys.
̶ This Keypad library is capable of supporting all of them and improves readability of the
code by hiding the pinMode() and digitalRead() function calls.
̶ No external pull-up resistors or diode protection is required because the library uses
internal pull-up resistors and ensures that all unused column pins are high-impedance.

// connect keypad row pins to


byte rowPins[4] = {A5, A4, 3, 2};
/* ROW0 to pin A5
ROW1 to pin A4
ROW2 to pin 3
ROW3 to pin 2 */

// connect keypad column pins to


byte colPins[3] = {12, 11, 10};
/* COL0 to pin 12
COL1 to pin 11
COL2 to pin 10 */

̶ Note: the Keypad library is part of the hardware abstraction libraries.


Download and installing keypad library
̶ The Keypad library is available through the Arduino IDE library manager when
connected to the internet, by simply using menu option:
> Sketch -> Include Library -> Manage Libraries...
̶ Then search for keypad and once found, select it so that the install button appears.

̶ Alternatively if the “keypad.zip” file is downloaded, simply use the menu option:
> Sketch -> Include Library -> Add .ZIP Library...
̶ Then search for the downloaded “keypad.zip” file and open it to install.

̶ Or unzip “keypad.zip” and then copy the unzipped “keypad” folder to the following
directory: “Libraries\Documents\My Documents\Arduino\libraries”

̶ Once the Keypad library is installed, a "#include <Keypad.h>" line needs to be added at
the top of the Sketch.
̶ Or select: “Sketch -> Include Library -> Keypad” and "#include <Keypad.h>" line will
automatically appears at the top of the Sketch

̶ Note: “File -> Examples -> Keypad ->” IDE path includes code examples of how to use
the Keypad library functions.
Example 1: Creating an instance of a Keypad class
#include <Keypad.h>
const byte ROWS = 4; // four rows
const byte COLS = 3; // three columns
char keys[ROWS][COLS] = { {'1','2','3'}, // 12 11 10
{'4','5','6'}, // A5-|-|-|-
{'7','8','9'}, // A4-|-|-|-
{'*','0','#'} }; // 3-|-|-|-
// 2-|-|-|-
byte rowPins[ROWS] = {A5, A4, 3, 2}; // connected keypad row pins
byte colPins[COLS] = {12, 11, 10}; // connected keypad column pins
Keypad NumKeys = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
void setup()
{
// “NumKeys.begin(makeKeymap(keys))” not required
NumKeys.setDebounceTime(10); // ms to wait before accepting new key press
NumKeys.setHoldTime(250); // required ms to hold a key button down
}
void loop()
{
char ckey = NumKeys.getKey();
if(ckey) // Check for a valid key.
{...};
}
Example 2: Creating an instance of a Keypad class
#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = { {'1','2','3'}, // C0 C1 C2
{'4','5','6'}, // R0-|-|-|-
{'7','8','9'}, // R1-|-|-|-
{'*','0','#'} }; // R2-|-|-|-
// R4-|-|-|-
byte rowPins[ROWS] = {A5, A4, 3, 2}; //connect keypad row pins
byte colPins[COLS] = {12, 11, 10}; //connect keypad column pins
Keypad NumKeys(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
void setup()
{
NumKeys.begin(makeKeymap(keys));
NumKeys.setDebounceTime(10); // ms to wait before accepting new key press
NumKeys.setHoldTime(250); // required ms to hold a key button down
}
void loop()
{
char ckey = NumKeys.getKey();
if(ckey != NO_KEY) // note: ‘NO_KEY’ = ‘\0’ (0x00 or false)
{... };
}
Creating an instance of a Keypad class
• Note
̶ “Keypad NumKeys = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS)”
̶ Or
̶ “Keypad NumKeys(makeKeymap(keys), rowPins, colPins, ROWS, COLS)”,
̶ Creates a Keypad object instance, that uses the selected row pins and column pins.

̶ Any Arduino pins in any order, can be connected to the matrix keypad.
̶ Do not to use the serial RX-pin0 and TX-pin1, used for serial coms and programing.
̶ If a key press detection seems to take a long time, then long delay()’s are probably
being use in the code.
̶ The same thing can happen if too many small delay()’s (e.g. 10ms, 20ms) are also used.
̶ Make sure the keypad is wired up to match the pin mappings.
̶ If incorrect pins are wired and already soldered, then it can be fixed by redefining the
pin mappings and/or key-map, to make the keypad work.
Function: NumKeys.begin(makeKeymap(keys))
• Description
̶ Initializes the internal “key-map” to be equal to user specified key-map.
• Function
̶ void begin(makeKeymap(userKeymap))
• Syntax
̶ NumKeys.begin(makeKeymap(keys));
• Parameters
̶ keys: user defined 2-dimensional key-map.
• Example
#include <keypad.h>
...
// Create the keypad
Keypad NumKeys(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

void setup(){
NumKeys.begin(makeKeymap(keys));
...
}
Function: NumKeys.setDebounceTime()
• Description
̶ Sets the amount of milliseconds to wait before accepting a new key press or key event.
̶ When a mechanical key switch is pressed, undesired multiple key contact bounce
activations occur.
̶ Key press contact bounce activations within the set debounce time delay frame, will
simply be ignored.
̶ This avoids multiple key entry for a single key press and this is called the "time delay"
debounce method.
• Function
̶ void setDebounceTime(unsigned int time)
• Syntax
̶ NumKeys.setDebounceTime(time);
• Parameters
̶ time: amount of milliseconds (unsigned int).
• Note
̶ If the setDebounceTime() function is not called, the default time is set to 10 ms.
Function: NumKeys.setHoldTime()
• Description
̶ Sets the amount of milliseconds the user must hold a key button down, until the hold
state is triggered.
̶ The key pressed value is returned only after the hold state is triggered.
̶ If a key button is released before the hold state is triggered, no key press value is
returned.
• Function
̶ void setHoldTime(unsigned int time)
• Syntax
̶ NumKeys.setHoldTime(time);
• Parameters
̶ time: amount of milliseconds (unsigned int).
• Note
̶ If the setHoldTime () function is not called, the default time is set to 500 ms.
Function: NumKeys.getKey()
• Description
̶ Used to get the key pressed value, if any.
̶ This function is non-blocking, code execution continues afterwards.
• Function
̶ char getKey()
• Syntax
̶ char ckey = NumKeys.getKey()
• Returns
̶ Character key pressed value (char).
• Example
#include <keypad.h>
...
char ckey = NumKeys.getKey();
// then check for a valid key
if(ckey) {...}
// or use
if(ckey != NO_KEY) {...} // note: ‘NO_KEY’ = ‘\0’ (0x00 or false)
Example: getKey() to serial send key pressed
#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
// define the symbols on the buttons of the keypad
char hexaKeys[ROWS][COLS] = { {'0','1','2','3'},
{'4','5','6','7'},
{'8','9','A','B'},
{'C','D','E','F'} };
byte rowPins[ROWS] = {3, 2, 1, 0}; //connect to keypad row pinouts
byte colPins[COLS] = {7, 6, 5, 4}; //connect to keypad column pinouts

// initialize a new instance of the Keypad class


Keypad kpd = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
void setup()
{
Serial.begin(9600);
}

void loop(){
char cKey = kpd.getKey();

if(cKey)
{
Serial.println(cKey);
}
}
Function: NumKeys.getKey()
• Note
̶ The getKey() function is non-blocking because a key can be pressed and held, but the
Arduino microcontroller continues processing the rest of the code.
̶ The function getKey() returns a key pressed value after the set debounce and hold time
ends, but it does not automatically repeat.

̶ However, every delay() function used will take processing time away from the keypad.
̶ Something as short as delay(250) can make the keypad very unresponsive.
̶ And the same thing will happen if a bunch of delay(10)'s is used throughout the code.

̶ When a key button is release, the key RELEASED event can be used to determine when
this occurs, only if the “Event Listener” feature of the Keypad library is used.
Function: NumKeys.waitForKey()
• Description
̶ This function waits until someone presses a keypad key.
̶ It blocks all other code from executing, until a key is pressed.
̶ That means no blinking LED's, no LCD screen updates, no further code execution with
the exception of interrupt routines.
• Function
̶ char waitForKey()
• Syntax
̶ char ckey = NumKeys.waitForKey()
• Returns
̶ Character key pressed value (char).
Function: NumKeys.getState()
• Description
̶ This function returns the current state of any key pressed and then released.
̶ There are four states that occur in sequence when a key is pressed and then released,
mainly: PRESSED, HOLD, RELEASED and IDLE.
̶ The PRESSED state only occurs after the set debounce time has expired, as set by the
setDebounceTime() function.
̶ The HOLD state only occurs after the set hold time has expired, as set by the
setHoldTime() function.
̶ After a key is released the RELEASED event occurs first, followed by a single IDLE event.
• Function
̶ byte getState() // returns constant byte Key-State: PRESSED, HOLD, RELEASED or IDLE
• Syntax
̶ byte State = NumKeys.getState()
• Returns
̶ PRESSED, HOLD, RELEASED or IDLE constants (byte).
Function: NumKeys.keyStateChanged()
• Description
̶ Let's you know when the key has changed from one state to another.
̶ For example, instead of just testing for a valid key you can test for when a key was
pressed.
• Function
̶ boolean keyStateChanged()
• Syntax
̶ boolean State = NumKeys.keyStateChanged()
• Returns
̶ true or false (boolean).
Function: NumKeys.addEventListener()
• Description
̶ After a getKey() function call, an event is trigger if the keypad is used.
• Function
̶ void addEventListener(keypadEvent)
• Syntax
̶ NumKeys.addEventListener(keypadEvent)
• Parameters
̶ keypadEvent: name of event function.
Example: addEventListener()
#include <Keypad.h>

byte rowPins[4] = {A5, A4, 3, 2}; // row pins of the keypad


byte colPins[3] = {12, 11, 10}; // column pins of the keypad

char keys[4][3] = { {'1','2','3'},


{'4','5','6'},
{'7','8','9'},
{'*','0','#'} };

Keypad kyp = Keypad(makeKeymap(keys), rowPins, colPins, 4, 3);


volatile boolean blinkLED = false;

void setup()
{
Serial.begin(9600);
kyp.setDebounceTime(10); // key press detected after 10ms
Kyp.setHoldTime(250); // key hold detected after 250ms
pinMode(LED_BUILTIN, OUTPUT); // sets digital pin as output
kyp.addEventListener(kypEvent); // add event listener for keypad
}
Example: addEventListener()
void loop()
{
char ckey = kyp.getKey();
if(ckey) Serial.println(ckey);

if(blinkLED)
{
digitalWrite(LED_BUILTIN,!digitalRead(LED_BUILTIN)); // blink LED
delay(100);
}
}

void kypEvent(KeypadEvent key) // Take care of special event


{
switch(kyp.getState())
{
case HOLD:
if(key == '*') blinkLED = true; //blink LED when holding * key
break;
case RELEASED:
if(key == '*') blinkLED = false; //stop blink after * key release
}
}
EXERCISE
1. Explain why the “Keypad” library does not require external pull-up resistors or diode
protection on the port pins connected to a matrix style keypad?
2. Design an Arduino C program without comments that demonstrates how to initialize the
internal “key-map” to be equal to a standard 3x4 matrix keypad. Arduino row pins 2,3,4 &
5 along with column pins 6, 7 & 8 are connected to a standard 3x4 matrix keypad. Also, set
the debounce time to 20ms and the key press hold-time to 200ms.
3. Describe the operation of the “setDebounceTime()” library function and discuss why is it
required?
4. Describe the operation of the “setHoldTime()” library function and explain how it works?
5. Create an Arduino C program without comments that serially transmits at 9600 bits/s, any
numeric key pressed on a standard 3x4 matrix keypad. The keypad rows are connected to
pins 8,7,6 & 5 and the columns are connected to pins 4, 3 & 2 on the Arduino UNO.
Additionally, if the ‘*’ key is pressed switch on the LED connected to pin 13 and if the ‘#’
key is pressed switch off the LED connected to pin 13.
6. Explain why the “getKey()” library function is non-blocking, when it returns a key pressed
value and whether it automatically repeats?
7. Describe how the “waitForKey()” library function works and explain its disadvantages?
8. Explain how the “getState()” library function works and discuss the different state that can
occur ?
EXERCISE
9. Design an Arduino C program without comments that serially transmits at 9600 baud rate,
the state of the ‘#’ key when pressed. The Arduino row pins A5, A4, 3 & 2 along with
column pins 12, 11 & 10 are connected to a standard 3x4 numeric matrix keypad.
Additionally, set the debounce time to 10 ms and the key press hold time to 250 ms. The
following serially transmitted strings: “PRESSED”, “HOLD”, “RELEASED” and “IDLE”, must
appear on separate lines as the different states occur.

You might also like