#include<reg51.h>
#include<intrins.h>
#define KEYPORT P3
#define uchar unsigned char
sbit line0=KEYPORT^0;
sbit line1=KEYPORT^1;
sbit line2=KEYPORT^2;
sbit line3=KEYPORT^3;
sbit RS=P2^2;
sbit RW=P2^1;
sbit E=P2^0;
uchar code dis[]={"0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15"};
bit iskeyinput()
{
KEYPORT=0x0f;
if((KEYPORT&0x0f)==0x0f)
return 0;
else
return 1;
}
uchar key_identify()
{
uchar linecode=0,rowcode=0;
uchar i;
uchar scancode=0xef;
for(i=0;i<4;i++)
{
KEYPORT=scancode;
if((KEYPORT&0x0f)==0x0f)
{
rowcode++;
scancode=scancode<<1|1;
}
else
{
if(line0==0)linecode=0;
if(line1==0)linecode=4;
if(line2==0)linecode=8;
if(line3==0)linecode=12;
break;
}
}
return linecode+rowcode;
}
void wait_key_release()
{
while(1)
{
KEYPORT=0x0f;
if((KEYPORT&0x0f)==0x0f)
break;
}
}
void delay(uchar ms)
{
uchar i;
while(ms--)
{
for(i=0;i<250;i++)
{
_nop_();_nop_();_nop_();_nop_();_nop_();
}
}
}
bit busy()
{
bit result;
RS=0;
RW=1;
E=1;
_nop_();_nop_();_nop_();_nop_();
result=(bit)(P1&0x80);
E=0;
return result;
}
void wcmd(uchar cmd)
{
while(busy());
RW=0;
E=0;
_nop_();_nop_();
P1=cmd;
_nop_();_nop_();_nop_();_nop_();
E=1;
_nop_();_nop_();_nop_();_nop_();
E=0;
}
void pos(uchar y,uchar x)
{
y&=0x1;
x&=0xF;
if(y==1)x|=0xc0;
if(y==0)x|=0x80;
wcmd(x);
}
void wdat(uchar dat)
{
while(busy());
RS=1;
RW=0;
E=0;
P1=dat;
_nop_();_nop_();_nop_();_nop_();
E=1;
_nop_();_nop_();_nop_();_nop_();
E=0;
}
void init()
{
wcmd(0x3c);
delay(1);
wcmd(0x0e);
delay(1);
wcmd(0x06);
delay(1);
wcmd(0x01);
delay(1);
}
void main(void)
{
uchar keycode;
unsigned int i;
uchar j;
init();
while(1)
{
while(!iskeyinput());
for(i=0;i<500;i++);
if(iskeyinput())
{
keycode=key_identify();
wait_key_release();
delay(10);
pos(0,keycode);
j=keycode;
while(dis[j]!=' ')
{
wdat(dis[j]);
j++;
}
// while(1);
}
}
}
|