Ninjaskit Keypad Library
I’ve just finished making a groovy little library for button matrix keypads.
Matrix keypads are fairly simple to use. They’ve got rows and columns, and each button connects a particular row to a given column.
To check if a switch is pressed – let’s say SW1 – you could put a digital high on Col1 and make Col2 – Col4 low. If Row1 is high then SW1 is pressed, otherwise SW1 is not pressed.
Reading the entire matrix is a matter of iteratively putting a high on each individual column and checking the state of each row.
Of course, this will only tell you the state of the keypad – if buttons are up or down. Generally speaking, you’ll need your program to perform some action when a button is pressed. The state of the keypad isn’t important; what is important is that something occurs when a button changes state. This paradigm is known as event-driven programming. The keypad library tracks the state of the keypad matrix and generates events when buttons are pressed or released.
Check out the example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
#include "ninjaskit/ninjaskit.h" #include "keypad/keypad.h" int main() { clock_setup(); Serial1.begin(57600); //create a list of row pins gpio_pin rows[] = { {PA, 0}, {PA, 1}, {PA, 2}, {PA, 3} }; //create a list of column pins gpio_pin cols[] = { {PA, 4}, {PA, 5}, {PA, 6}, {PA, 7 }}; //create a keypad with four rows and four columns - 16 buttons total Keypad<4, 4> keypad(rows, cols); while(true) { etk::sleep_ms(10); //read the state of the keypad and generate events if necessary keypad.read_keypad(); //while there are events queued up while(keypad.get_n_events()) { //get the next event auto event = keypad.get_event(); //if it's a button press if(event.type == BUTTON_PRESS_EVENT) Serial1.print("button ", event.button, " has been pressed\r\n"); //if it's a button release if(event.type == BUTTON_RELEASE_EVENT) Serial1.print("button ", event.button, " has been released\r\n"); } } } |