#include<reg51.h>
#include<intrins.h>
#define uint unsigned int
#define uchar unsigned char
//這三個(gè)引腳參考資料
sbit E=P2^7; //1602使能引腳
sbit RW=P2^6; //1602讀寫引腳
sbit RS=P2^5; //1602數(shù)據(jù)/命令選擇引腳
void init()
{
TMOD=0X00;
TH0=0X03;
TL0=0X32;
IE=0X82;
TR0=1;
}
/********************************************************************
* 名稱 : Delay_1ms()
* 功能 : 延時(shí)子程序,延時(shí)時(shí)間為 1ms * x
* 輸入 : x (延時(shí)一毫秒的個(gè)數(shù))
* 輸出 : 無
***********************************************************************/
void Delay_1ms(uint i)//1ms延時(shí)
{
uchar x,j;
for(j=0;j<i;j++)
for(x=0;x<=148;x++);
}
void delay()
{
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
}
bit Busy(void)
{
bit busy_flag = 0;
RS = 0;
RW = 1;
E = 1;
delay();
busy_flag = (bit)(P0 & 0x80);
E = 0;
return busy_flag;
}
void wcmd(uchar del)
{
while(Busy());
RS = 0;
RW = 0;
E = 0;
delay();
P0 = del;
delay();
E = 1;
delay();
E = 0;
}
void wdata(uchar del)
{
while(Busy());
RS = 1;
RW = 0;
E = 0;
delay();
P0 = del;
delay();
E = 1;
delay();
E = 0;
}
void L1602_init(void)
{
wcmd(0x38);
Delay_1ms(5);
wcmd(0x38);
Delay_1ms(5);
wcmd(0x38);
Delay_1ms(5);
wcmd(0x38);
wcmd(0x08);
wcmd(0x0c);
wcmd(0x06);
wcmd(0x01);
}
void L1602_char(uchar hang,uchar lie,char sign)
{
uchar a;
if(hang == 1) a = 0x80;
if(hang == 2) a = 0xc0;
a = a + lie - 1;
wcmd(a);
wdata(sign);
}
void L1602_string(uchar hang,uchar lie,uchar *p)
{
uchar a,b=0;
if(hang == 1) a = 0x80;
if(hang == 2) a = 0xc0;
a = a + lie - 1;
while(1)
{
wcmd(a++);
if((*p == '\0')||(b==16)) break;
b++;
wdata(*p);
p++;
}
}
uchar Keyscan(void)
{
uchar i,j, temp, Buffer[4] = {0xfe, 0xfd, 0xfb, 0xf7};
for(j=0; j<4; j++)
{
P1 = Buffer[j];
temp = 0x10;
for(i=0; i<4; i++)
{
if(!(P1 & temp))
{
return (i+j*4);
}
temp <<= 1;
}
}
}
void Main(void)
{
uchar Key_Value; //讀出的鍵值
L1602_init();
init();
L1602_string(1,16," 4*4 KeyBoard ");
L1602_string(2,16,"You Press The ");
for(Key_Value=15;Key_Value>0;Key_Value--)
{
wcmd(0x18);
Delay_1ms(250);
Delay_1ms(250);
}
while(1)
{
P1 = 0xf0;
if(P1 != 0xf0)
{
Delay_1ms(20); //按鍵消抖
if(P1 != 0xf0)
{
Delay_1ms(20); //按鍵消抖
if(P1 != 0xf0)
{
Key_Value = Keyscan();
}
}
}
L1602_char(2,30,Key_Value / 10 + 48);
L1602_char(2,31,Key_Value % 10 + 48);
}
}
void timer0() interrupt 1
{
}