Saturday, May 2, 2015

89C51 Interfacing of 4 x 4 matrix keypad


This tutorial shows how to interface 4x4 matrix keypad with 8051 microcontroller. Matrix keypads are used for entering numbers and alphabets commonly used in password based security system and code lock projects.

Objective:
1. Interface of 4x4 Keypad
2. Sending Key data to Serial port

Circuit:


Program:

//www.circuits4you.com
//4x4 Matrix Keypad Interfacing

#include <reg51.h>

sbit X1=P2^0;
sbit X2=P2^1;
sbit X3=P2^2;
sbit X4=P2^3;

sbit Y1=P2^4;
sbit Y2=P2^5;
sbit Y3=P2^6;
sbit Y4=P2^7;


unsigned char scankeys();
unsigned char decodekey(unsigned char key);
void delay();
unsigned char key;

void main()
{
 //Initialize Serial
 TH1=0xFD;   //9600 Baud rate at 11.0592MHz
 TMOD=0x20;  //Timer 1 in 8-bit Auto relaod mode
 SCON=0x50;  //REN=1 and Serial in 8-bit UART mode 1
 TR1=1;  //Start Timer

 while(1)
 {
  key=scankeys();  //Get which key is pressed
  if(key != 0)     //If key is pressed then only send it to serial
  {
   SBUF=key;
   while(TI==0);   //Wait until serial transmission completes
   TI=0;
  }
 }

}


unsigned char scankeys()
{
   key=0;
   
   //Keep X1 High and check status of Y
   P2=0xFE;
   if(P2 != 0xFE)
   {key=P2;}
   
   //Keep X2 High and check status of Y
   P2=0xFD;
   if(P2 != 0xFD)
   {key=P2;}

   //Keep X3 High and check status of Y
   P2=0xFB;
   if(P2 != 0xFB)
   {key=P2;}

   //Keep X5 High and check status of Y
   P2=0xF7;
   if(P2 != 0xF7)
   {key=P2;}
   
   if(key !=0)
   {key=decodekey(key);} //Send the hex value to get ASCII code

   delay();      //Delay for key
   return key;
}

void delay()
{
 int i;
 for(i=0;i<10000;i++); //Adjust delay for key repetition rate 
}

unsigned char decodekey(unsigned char key)
{
 unsigned char dkey;
 if(key==0xEE) {dkey = '1';}  //ASCII Codes for keys
 if(key==0xDE) {dkey = '2';}
 if(key==0xBE) {dkey = '3';}
 if(key==0x7E) {dkey = '4';}
 
 if(key==0xED) {dkey = '5';}
 if(key==0xDD) {dkey = '6';}
 if(key==0xBD) {dkey = '7';}
 if(key==0x7D) {dkey = '8';}

 if(key==0xEB) {dkey = '9';}
 if(key==0xDB) {dkey = '0';}
 if(key==0xBB) {dkey = 'A';}
 if(key==0x7B) {dkey = 'B';}

 if(key==0xE7) {dkey = 'C';}
 if(key==0xD7) {dkey = 'D';}
 if(key==0xB7) {dkey = 'E';}
 if(key==0x77) {dkey = 'F';}
  
 return dkey;
}

Program is tested on hardware requires key debounce  mechanism using delay.



No comments:

Post a Comment