4×4 Keypad
Introduction
A keypad serves as an input device, detecting and processing key presses from the user. A 4×4 keypad comprises 4 rows and 4 columns, with switches positioned at each intersection. Pressing a key connects a specific row and column, allowing the system to recognize the pressed key.
To detect a keypress, configure the rows as outputs and the columns as inputs. By sending signals through the rows and then reading the columns, you can identify both the occurrence and location of a keypress.
For further details on keypads and their usage, see the “4×4 Keypad” section in Sensors and Modules.
Example
In this section, we’ll interface a 4×4 keypad with the AT89S52 (8051) microcontroller to display the pressed key on a 16×2 LCD.
Interfacing Diagram
Keypad interfacing with 8051
Program
/*
4x4 Keypad Interfacing with 8051(AT89s52)
http://www.electronicwings.com
*/
#include<reg52.h>
#include<stdio.h>
#include<string.h>
#include "LCD_8_bit.h" /* 16x2 LCD header file*/
#define keyport P1
sbit RS = P3^5; /* RS(register select) for LCD16x2 */
sbit RW = P3^6; /* RW(Read/write) for LCD16x2 */
sbit ENABLE = P3^7; /* EN(Enable) pin for LCD16x2*/
unsigned char keypad[4][4] = {{'7','8','9','/'},
{'4','5','6','x'},
{'1','2','3','-'},
{' ','0','=','+'} };
unsigned char colloc, rowloc;
unsigned char key_detect()
{
keyport=0xF0; /*set port direction as input-output*/
do
{
keyport = 0xF0;
colloc = keyport;
colloc&= 0xF0; /* mask port for column read only */
}while(colloc != 0xF0); /* read status of column */
do
{
do
{
delay(20); /* 20ms key debounce time */
colloc = (keyport & 0xF0); /* read status of column */
}while(colloc == 0xF0); /* check for any key press */
delay(1);
colloc = (keyport & 0xF0);
}while(colloc == 0xF0);
while(1)
{
/* now check for rows */
keyport= 0xFE; /* check for pressed key in 1st row */
colloc = (keyport & 0xF0);
if(colloc != 0xF0)
{
rowloc = 0;
break;
}
keyport = 0xFD; /* check for pressed key in 2nd row */
colloc = (keyport & 0xF0);
if(colloc != 0xF0)
{
rowloc = 1;
break;
}
keyport = 0xFB; /* check for pressed key in 3rd row */
colloc = (keyport & 0xF0);
if(colloc != 0xF0)
{
rowloc = 2;
break;
}
keyport = 0xF7; /* check for pressed key in 4th row */
colloc = (keyport & 0xF0);
if(colloc != 0xF0)
{
rowloc = 3;
break;
}
}
if(colloc == 0xE0)
{
return(keypad[rowloc][0]);
}
else if(colloc == 0xD0)
{
return(keypad[rowloc][1]);
}
else if(colloc == 0xB0)
{
return(keypad[rowloc][2]);
}
else
{
return(keypad[rowloc][3]);
}
}