Created
October 18, 2012 22:24
-
-
Save Crenshinibon/3915145 to your computer and use it in GitHub Desktop.
Basic keyboard polling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Key { | |
byte id; | |
boolean pressed; | |
uint8_t bounceKey; | |
Key(byte id) : id(id), pressed(false), bounceKey(NOT_BOUNCING) {}; | |
} | |
boolean toggleKey(struct Key *key) { | |
key->bounceKey = checkStillBouncing(key->bounceKey); | |
if(key->bounceKey == NOT_BOUNCING){ | |
key->bounceKey = debounceKey(); | |
key->pressed ? key->pressed = false : key->pressed = true; | |
return true; | |
} | |
return false; | |
} | |
const uint8_t cols[COL_COUNT] = {11,3,4,5,6,7,8}; | |
const uint8_t rows[ROW_COUNT] = {A0,10,9,A3,A4,A5}; | |
Key * const NOKEY = new Key(0xFF); | |
Key * const ESC = new Key(0x00); | |
Key * const F1 = new Key(0x01); | |
// ... | |
// omitted keys | |
// ... | |
Key * const CTRLL = new Key(0x23); | |
Key * const CMDL = new Key(0x24); | |
Key * const SPACE = new Key(0x25); | |
Key * const keyMatrix[COL_COUNT][ROW_COUNT] = | |
{ | |
{ESC,ZIRKONFLEX,TAB,M3,M2L,NOKEY}, | |
{F1,N1,X,U,UE,M4}, | |
{F2,N2,V,I,OE,ALTL}, | |
{F3,N3,L,A,AE,CTRLL}, | |
{F4,N4,C,E,P,CMDL}, | |
{F5,N5,W,O,Z,SPACE}, | |
{NOKEY,BACK,ENTF,ENTER,NOKEY,NOKEY} | |
} | |
boolean keyChanged = false; | |
Key * pressedKeys[MAX_KEYS_PRESSED] = {0}; | |
uint8_t pressedKeyIndex = 0; | |
static void resetKeys(){ | |
for(int i = 0; i < pressedKeyIndex; i++){ | |
pressedKeys[i] = NOKEY; | |
} | |
pressedKeyIndex = 0; | |
keyChanged = false; | |
} | |
static void scanKeys(){ | |
//iterate over columns | |
for(int currentColumn = 0; currentColumn < COL_COUNT; currentColumn ++){ | |
digitalWrite(cols[currentColumn],HIGH); | |
//scan rows | |
for(int y = 0; y < ROW_COUNT; y++){ | |
Key* key = keyMatrix[currentColumn][y]; | |
if(key != NOKEY){ | |
int state = digitalRead(rows[y]); | |
if((state == HIGH && !key->pressed) || (state == LOW && key->pressed)){ | |
if(toggleKey(key)){ | |
keyChanged = true; | |
} | |
} | |
//collect report data, only pressed keys need to be sent to the computer | |
if(key->pressed){ | |
if(pressedKeyIndex < MAX_KEYS_PRESSED){ | |
pressedKeys[pressedKeyIndex] = key; | |
pressedKeyIndex++; | |
} | |
} | |
} | |
} | |
digitalWrite(cols[currentColumn],LOW); | |
} | |
} | |
void loop() { | |
resetKeys(); | |
scanKeys(); | |
sendKeyState(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment