Ever want to use a 3×4 Keypad? These keypads from Adafruit can be used for numeric data entry or for access control for a security system. Our example allows you to input a multiple digit entry with a “enter key” (#) and a “cancel key” (*). In our example, we will assemble a file name for submission to a sd card, but you can drop that off if you don’t need that.
I plugged the keypad cable into a male extended length header, and plugged in directly into pins 2-8 on the arduino.
Download the library file at http://playground.arduino.cc/Code/Keypad and install into your library folder.
Become the Maker you were born to be. Try Arduino Academy for FREE!
The following sketch will allow a key sequence of at least 6 digits. You can enlarge the string if you need more digits. It displays each digit as entered in the serial monitor,and allows you to press * to cancel and start over if you make a mistake.
Thanks to Mike McRoberts and Mark Stanley for their help!
Also see our RFId and Fingerprint scanner tutorials!
#include <Keypad.h>
const byte ROWS = 4; //four rows const byte COLS = 3; //three columns char keys[ROWS][COLS] = { {'1','2','3'}, {'4','5','6'}, {'7','8','9'}, {'*','0','#'} }; byte rowPins[ROWS] = {8, 7, 6, 5}; //connect to the row pinouts of the kpd byte colPins[COLS] = {4, 3, 2}; //connect to the column pinouts of the kpd
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
char entryStr[8];
int i=0;
void setup(){
Serial.begin(9600);
}
void loop(){
char key = keypad.getKey();
if (key){
if (key == ‘*’){
memset(entryStr, 0, sizeof(entryStr));
i=0;
key=0;
Serial.println(“”);
Serial.println(“Canceled”);
} else if (key != ‘#’){
entryStr[i]= key;
i++;
Serial.print(key);
}
else {
Serial.println(“”);
i=0;
key=0;
String fileName = entryStr;
memset(entryStr, 0, sizeof(entryStr));
fileName = fileName + “.mp3”;
Serial.println(fileName);
}
}
}