Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / IoT / Arduino

ADKeyboard Library for Arduino

5.00/5 (2 votes)
10 Jan 2014CPOL1 min read 11.4K   182  
A library for 5-button analog keypad

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.

C++
// include the header file
#include <AdKeyboard.h>
// instantiate it on Analog0 of the arduino board
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.

C++
void setup() {
  Serial.begin(9600);
  adKeyboard.setClickCallback(clickHandler);
  adKeyboard.setPressCallback(pressHandler);
  adKeyboard.setTwoPressCallback(twoPressHandler);
} 

And the callback functions:

C++
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.

C++
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)