Interfacing keypad with 8051.
Code :
#include<reg51.h> // Include 8051 library.
sbit r0 = P2^0; // Set bit for row 0.
sbit r1 = P2^1; // Set bit for row 1.
sbit r2 = P2^2; // Set bit for row 2.sbit r3 = P2^3; // Set bit for row 3.
sbit c0 = P2^4; // Set bit for column 0.
sbit c1 = P2^5; // Set bit for column 1.
sbit c2 = P2^6; // Set bit for column 2.
sbit c3 = P2^7; // Set bit for column 3.
void ser_init(); // Initialize serial communications
void tx(unsigned char w); // transmit character of string.
void main() // Main function starts
{
scr_init(); // Serial function calling
while(1) // Infinite loop.
{
r0=0;r1=1;r2=1;r3=1; // row 0 active others inactive.
if(c0==0) // if column 0 is active.
{
tx('7'); // display 7
while(c0==0); // While column 0 is active.
}
if(c1==0)
{
tx('8');
while(c1==0);
}
if(c2==0)
{
tx('9');
while(c2==0);
}
if(c3==0)
{
tx('/');
while(c3==0);
}
r0=1;r1=0;r2=1;r3=1;
if(c0==0)
{
tx('4');
while(c0==0);
}
if(c1==0)
{
tx('5');
while(c1==0);
}
if(c2==0)
{
tx('6');
while(c2==0);
}
if(c3==0)
{
tx('*');
while(c3==0);
}
r0=1;r1=1;r2=0;r3=1;
if(c0==0)
{
tx('1');
while(c0==0);
}
if(c1==0)
{
tx('2');
while(c1==0);
}
if(c2==0)
{
tx('3');
while(c2==0);
}
if(c3==0)
{
tx('-');
while(c3==0);
}
r0=1;r1=1;r2=1;r3=0;
if(c0==0)
{
tx('C');
while(c0==0);
}
if(c1==0)
{
tx('0');
while(c1==0);
}
if(c2==0)
{
tx('=');
while(c2==0);
}
if(c3==0)
{
tx('+');
while(c3==0);
}
}
}
void tx(unsigned char w) // Transmit function.
{
SBUF = w; // SBUF temporary buffer location where character is stored.
while(TI==0); // Wait until transmission completed flag gets high. TI=0; // Once high , make it zero for the next character.
}
void ser_init() // Serial transmission function
{
SCON = 0X50; // Mode 1 (8-bit UART )
TMOD = 0X20; // Timer 1 in Mode 2. TH1 = 0XFD; // Baud rate of 9600.
TR1 = 1; // Timer run flag enabled.
}
A keypad is connected to Port 2 of microcontroller.
Rows are connected to first 4 data pins
Columns are connected to last 4 pins .
A virtual terminal is connected to port 3 for serial comm.
Note : Do not connect keypad to port 0 as it does not have an internal pull up resistor.
As you press the keys it will get displayed on the screen.
Comments
Post a Comment