This blog post explains how to interface matrix keypad with cortex m4
Procedure:
- Power: In the PCONP register, set the PCGPIO bit
- Configure all the Keypad pins as GPIO using IOCON3_0 to IOCON3_7
- Configure all the row pins as output and make it HIGH
- Configure all the column pins as input and make it HIGH
- Configure all the LCD pins as output and Initialize LCD
- Make a row pin Zero and check all the four column lines one by one for zero
- If any key is pressed, the corresponding column will get zero
- Read the key value and display it in LCD
Interface Matrix key pad with cortex m4 -C Source code
#include <LPC407x_8x_177x_8x.h>
#include "LCD.h"
#define keyportc LPC_GPIO3->CLR
#define keyports LPC_GPIO3->SET
#define COL1 (LPC_GPIO3->PIN & 0x10)
#define COL2 (LPC_GPIO3->PIN & 0x20)
#define COL3 (LPC_GPIO3->PIN & 0x40)
#define COL4 (LPC_GPIO3->PIN & 0x80)
unsigned char k=0,key=0,i=0;
unsigned char Lcd_LINE1[]={"KEYPAD DEMO: "};
unsigned char get_key(void);
int main(void)
{
//1. Set the PCGPIO bit
LPC_SC->PCONP |= (1<<15);
//2. Configure all Keypad pins as GPIO
LPC_IOCON->P3_0 = 0x00;
LPC_IOCON->P3_1 = 0x10;
LPC_IOCON->P3_2 = 0x10;
LPC_IOCON->P3_3 = 0x10;
LPC_IOCON->P3_4 = 0x10;
LPC_IOCON->P3_5 = 0x10;
LPC_IOCON->P3_6 = 0x10;
LPC_IOCON->P3_7 = 0x10;
//3. Configure all the row pins as output and make it HIGH
// Configure all the column pins as input and make it HIGH
LPC_GPIO3->DIR = 0x0F;
LPC_GPIO3->PIN = 0x0F;
//5. Configure all the LCD pins as GPIO outputs and Initialize LCD
lcd_init();
//Send First line command
lcd_command(0x80);
//Send 16 characters from the line1 array
for(i=0;Lcd_LINE1[i]!='\0';i++)
{
lcd_data(Lcd_LINE1[i]);
delay_ms(50);
}
delay_ms(1000);
while (1)
{
if(get_key()!=0){
lcd_command(0xc0);
if(key<=10)lcd_data(key-1+'0');
else lcd_data(key-11+'A');
}
delay_ms(100);
}
}
unsigned char get_key(void)
{
LPC_GPIO3->PIN=0x0F;
k=1;
for(i=0;i<4;i++){
keyportc |=(0x01<<i); //Scan for a Key by sending '0' on ROWS
lcd_command(0xc0);
if(COL1==0){ //when a key pressed numbers 1--16 will be returned
key = k+0;
while(COL1==0);
return key;
}
if(COL2==0){
key = k+1;
while(COL2==0);
return key;
}
if(COL3==0){
key = k+2;
while(COL3==0);
return key;
}
if(COL4==0){
key = k+3;
while(COL4==0);
return key;
}
k+=4;
keyports |=(0x01<<i);
}
return 0;
}