Class library for a 4x4 keypad connected to a MCP23008 I2C IO Expander.
MCP23008_Keypad.cpp
- Committer:
- grantphillips
- Date:
- 2016-04-05
- Revision:
- 3:7d6b9684595c
- Parent:
- 0:6f83aeb11f9a
File content as of revision 3:7d6b9684595c:
#include "MCP23008_Keypad.h" #include "mbed.h" // Keypad layout: // [row][col] Col0 Col1 Col2 Col3 char const kpdLayout[4][4] = {{'1' ,'2' ,'3' ,'A'}, //row0 {'4' ,'5' ,'6' ,'B'}, //row1 {'7' ,'8' ,'9' ,'C'}, //row2 {'*' ,'0' ,'#' ,'D'}}; //row3 //NIBBLE LOW=0000, HIGH= 0111 1011 1101 1110 Col (x) const char KpdInMask[4] ={0xe0,0xd0,0xb0,0x70}; //NIBBLE HIGH=1111, LOW= 0111 1011 1101 1110 Rows (y) const char KpdOutMask[4]={0xfe,0xfd,0xfb,0xf7}; MCP23008_Keypad::MCP23008_Keypad(PinName SDApin, PinName SCLpin, int MCP23008Address) : i2c(SDApin, SCLpin) { char cmd[2]; _addr = MCP23008Address; i2c.frequency(100000); //set I2C frequency to 100Khz cmd[0] = 0x00; //IODIR register cmd[1] = 0xf0; //Bit7 - 4 are inputs and rest outputs i2c.write(_addr, cmd, 2); //write IODIR setting to MCP23008 } char MCP23008_Keypad::ReadKey() { char KeyValue, Done=0; uint16_t y, x; char cmd[2]; //delay_ms(ContactBounceTime); //warning no contact bounce protection //call read_key more than once with delay //between if key stay constant then key is pressed y = 0; while((y < 4) && (!Done)) { cmd[0] = 0x09; cmd[1] = KpdOutMask[y]; i2c.write(_addr, cmd, 2); //write mask value to MCP23008 GPIO register wait(0.01); cmd[0] = 0x09; i2c.write(_addr, cmd, 1); i2c.read(_addr, cmd, 1); KeyValue = cmd[0] & 0xf0; //read 4 MSB bits from MCP23008 GPIO register if(KeyValue == KpdInMask[0]) x = 0; else if(KeyValue == KpdInMask[1]) x = 1; else if(KeyValue == KpdInMask[2]) x = 2; else if(KeyValue == KpdInMask[3]) x = 3; else { KeyValue='\0'; //more than one key was pressed or no key in this row. x=9; } if(x != 9) { Done = 1; //valid key found KeyValue = kpdLayout[x][y]; //convert to a character eg. '1','2','3','#','*' } y++; } return(KeyValue); }