Projects › Projects › How to interface keypad with 8051 microcontroller (AT89C51) › interfacing keypad and
interfacing keypad and seven segment with 89C51
C Code:
//////////////////////////////////////////////////////////////////////////
#include <AT89X51.H>
#include <my.h> //delay built in function
#define led P1_0
char unit, tens,e = 0;
char scan (void);
#define row1 P3_0
#define row2 P3_1
#define row3 P3_2
#define row4 P3_3
#define col1 P3_4
#define col2 P3_5
#define col3 P3_6
#define col4 P3_7
unsigned char ch = 0;
unsigned int ar[1] = 0;
unsigned int font[10];
unsigned char counter = 0;
void decode(void)
{
unit = e % 10;
tens = (e % 100) / 10;
unit = font[unit];
tens = font[tens];
}
void display(void)
{
int i = 0;
for(i = 0; i < 100; i++)
{
P0 = unit;
P2_1 = 0;
delay(1);
P2_1 = 1;
P0 = tens;
P2_0 = 0;
delay(1);
P2_0 = 1;
}}
void main (void)
{ // 7 seg equivalent code
font[0] = 0x3f;
font[1] = 0x06;
font[2] = 0x5b;
font[3] = 0x4f;
font[4] = 0x66;
font[5] = 0x6d;
font[6] = 0x7d;
font[7] = 0x07;
font[8] = 0x7f;
font[9] = 0x6f;
while(1)
{
decode();
display();
ch = scan();
if(ch != 100)
{
if(ch == 13) // % symbol in keypad causes reset
{
e = 0;
counter= 0;
}
if(ch < 10)
{
e = ch;
if(counter < 2)
{
ar[counter] = ch;
counter++;
if(counter == 2)
{
e = ar[0] * 10;
e = e + ar[1];
decode();
display();
counter = 0;
}}
}}} }
char scan (void)
{
row1 = 0;
row2 = 1;
row3 = 1;
row4 = 1;
col1 = 1;
col2 = 1;
col2 = 1;
col4 = 1;
if (col1 == 0)
{
led = 1;
delay(100);
led = 0;
return 1;
}
if (col2 == 0)
{
led = 1;
delay(100);
led = 0;
return 2;
}
if (col3 == 0)
{
led = 1;
delay(100);
led = 0;
return 3;
}
if (col4 == 0)
{
led = 1;
delay(100);
led = 0;
return 13;
}
row1 = 1;
row2 = 0;
if (col1 == 0)
{
led = 1;
delay(100);
led = 0;
return 4;
}
if (col2 == 0)
{
led = 1;
delay(100);
led= 0;
return 5;
}
if (col3 == 0)
{
led = 1;
delay(100);
led = 0;
return 6;
}
if (col4 == 0)
{
led = 1;
delay(100);
led = 0;
return 14;
}
row2 = 1;
row3 =0;
if (col1 == 0)
{
led = 1;
delay(100);
led = 0;
return 7;
}
if (col2 == 0)
{
led = 1;
delay(100);
led = 0;
return 8;
}
if (col3 == 0)
{
led = 1;
delay(100);
led = 0;
return 9;
}
if (col4 == 0)
{
led = 1;
delay(100);
led = 0;
return 15;
}
row3 = 1;
row4 = 0;
if (col1 == 0)
{
led = 1;
delay(100);
led = 0;
return 11;
}
if (col2 == 0)
{
led = 1;
delay(100);
led = 0;
return 0;
}
if (col3 == 0)
{
led = 1;
delay(100);
led = 0;
return 12;
}
if (col4 == 0)
{
led = 1;
delay(100);
led = 0;
return 16;
}
row4 = 1;
return 100;
}