How to input a multiple digits number using the keypad?

Arduino keypad libary returns only a single key when reading. how can I read a multi digit input and put it into a numeric variable? How can read a number from keypad to set servo motor's angle, set temperature threshold... For example, if I press "120" keys on keypad, the value of an integer variable is 120. if I press "12" keys on keypad, the value of an integer variable is 12.
ANSWER

Anwser

There are some ways to input the multiple digits number to a integer variable. The simplest way is described as follows:

When a key is pressed:

The advantages of this method are simple and able to get one-digit number, two-digit number, three-digit, four-digit number, or any-digit number WITHOUT pre-defineing the mumber of digit.

Arduino Code for Reading the Multiple Digit Number

#include <Keypad.h> const int ROW_NUM = 4; //four rows const int COLUMN_NUM = 3; //three columns char keys[ROW_NUM][COLUMN_NUM] = { {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}, {'*', '0', '#'} }; byte pin_rows[ROW_NUM] = {9, 8, 7, 6}; //connect to the row pinouts of the keypad byte pin_column[COLUMN_NUM] = {5, 4, 3}; //connect to the column pinouts of the keypad Keypad keypad = Keypad( makeKeymap(keys), pin_rows, pin_column, ROW_NUM, COLUMN_NUM ); String inputString; long inputInt; void setup() { Serial.begin(9600); inputString.reserve(10); // maximum number of digit for a number is 10, change if needed } void loop() { char key = keypad.getKey(); if (key) { Serial.println(key); if (key >= '0' && key <= '9') { // only act on numeric keys inputString += key; // append new character to input string } else if (key == '#') { if (inputString.length() > 0) { inputInt = inputString.toInt(); // YOU GOT AN INTEGER NUMBER inputString = ""; // clear input // DO YOUR WORK HERE } } else if (key == '*') { inputString = ""; // clear input } } }

The wiring diagram for above code:

Arduino Keypad Wiring Diagram

Image is developed using Fritzing. Click to enlarge image

※ NOTE THAT:

In the above code, inputString.reserve(10) is used to prevent the memory fragmentation issue on String library

To learn more about keypad, see Arduino - Keypad tutorial

See Also

※ OUR MESSAGES