A library to control a 4x3 matrix style keypad.
Keypad
A basic library to read in pushbutton presses from the Sparkfun Keypad - 12 Button.
The product site and documentation for the keypad is here. https://www.sparkfun.com/products/8653
Diff: Keypad.cpp
- Revision:
- 0:fef7520ff0a6
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Keypad.cpp Wed Mar 11 14:50:03 2015 +0000 @@ -0,0 +1,109 @@ +#include "Keypad.h" + +#include "mbed.h" + +// create a Keypad object +Keypad::Keypad(PinName row1, PinName row2, PinName row3, PinName row4, PinName col1, PinName col2, PinName col3) + : rows (row1, row2, row3, row4),cols (col1, col2, col3) +{ +} + + + +int Keypad::getKey() +{ + //int row_hit = getRowHit(); // get row that was hit (1-4) + //int col_hit = getColHit(); // get col that was hit (1-3) + char key = decode(); + last_key_hit = key; + return key; +} + +int Keypad::isNewAndPressed() // Is the button a new button press? +{ + col_hit = getColHit(); + row_hit = getRowHit(); + char key = decode(); + if (key == last_key_hit) { + // No new button has been hit + return 0; + } else if(key == ' ') { //button has been released + last_key_hit = key; + return 0; + } else { + return 1; + } +} + +//Private memeber function implementations below + +void Keypad::tristate_all() +{ + // simulate tri-state by changing mode to PullNone + rows.input(); + rows.mode(PullNone); + cols.input(); + cols.mode(PullNone); +} + +int Keypad::log2(int num) +{ + int count = -1; + while(num > 0) { + num = num >> 1; + ++count; + } + return count; +} + +char Keypad::decode() +{ + char dig = ' '; + if (row_hit >= 0 && row_hit < 3 && col_hit != -1) { + // output the character for buttons 1-9 pressed on the keypad + int key_pressed = row_hit * 3 + col_hit + 1; + dig = (char)(((int)'0')+key_pressed); + return dig; + } else if(row_hit == 3) { // the last row was hit + switch(col_hit) { + case 0 : + dig = '*'; + break; + case 1 : + dig = '0'; + break; + case 2 : + dig = '#'; + break; + } + } + return dig; +} + +int Keypad::getRowHit() +{ + //Set cols to output and output HIGH, read rows for any inputs that are high. + cols.output(); + rows.input(); + rows.mode(PullDown); + wait_ms(100); + cols = 0xF; + int row_hit = rows.read(); + tristate_all(); + row_hit = log2(row_hit); + return row_hit; +} + +int Keypad::getColHit() +{ + //Set rows to output and output HIGH, read cols for any inputs that are high. + rows.output(); + cols.input(); + cols.mode(PullDown); + wait_ms(100); // Give time to set up pin modes + rows = 0xF; + int col_hit = cols.read(); + tristate_all(); + col_hit = log2(col_hit); + return col_hit; +}