Introduction
I have just bought a 5-button keypad from cooking-hacks. I like it, because it is useful for simple tasks and costs only 1 analog pin on your Arduino. The usage is also simple. You read different values from the analog pin for each button, therefore you can understand which button is pressed. Here is the keyboard and its sample code. What I did is to package them up into a library.
Using the Code
When you place the library files (AdKeyboard.cpp, AdKeyboard.h) in your libraries folder of Arduino IDE, you are ready to use it in your project.
#include <AdKeyboard.h>
AdKeyboard adKeyboard(0);
You can attach your codes to the events by providing callback functions to the keyboard object in the setup. There are 3 events that I have implemented.
- Click event: Just simple press & release event.
- Press event: Press & hold event. When you hold a key for a while (default value is 2sec.), attached callback function is executed if provided.
- Two-press event: Like press event, but you have to hold down two keys concurrently to fire this event. There is a tricky point here. You should press higher-indexed key first, because lower-indexed key masks higher ones because of the hardware implementation.
Let's attach callback functions to the adKeyboard
object.
void setup() {
Serial.begin(9600);
adKeyboard.setClickCallback(clickHandler);
adKeyboard.setPressCallback(pressHandler);
adKeyboard.setTwoPressCallback(twoPressHandler);
}
And the callback functions:
void clickHandler(int key) {
Serial.print("clickHandler: ");
Serial.println(key);
}
void pressHandler(int key) {
Serial.print("pressHandler: ");
Serial.println(key);
}
void twoPressHandler(int k1, int k2) {
Serial.print("twoPressHandler: ");
Serial.print(k1);
Serial.print(" ");
Serial.println(k2);
}
There is one point left. You have to monitor keyboard in your main loop.
void loop() {
adKeyboard.update();
}
That is it. Now you have a 5-button keypad for your projects. Enjoy it!
You can download the source code from the link at the top of this tip.