|
# include<reg52.h>
# define uint unsigned int
# define uchar unsigned char
sbit DATA=P3^2;
sbit rs=P2^6; //1602引腳定義
sbit rw=P2^5;
sbit e=P2^7;
uchar dat,num;
uchar code table[]="0123456789ABCDEF";
uchar code table1[]="Receive:"; //液晶固定部分顯示
uchar code table2[]="Re_data:0x";
void write_data (uchar dat); //1602寫數(shù)據(jù)
void write_com (uchar com); //1602寫命令
unsigned char pow(unsigned char n,unsigned char m); //n的m次方函數(shù)
uchar receive(void); //接收處理函數(shù)
void gd(); //液晶固定部分顯示
void delay (uint xms) //1602延時
{
uint i,j;
for (i = xms; i > 0; i--)
for (j = 110; j > 0; j--);
}
void delay1(unsigned char t)//延時程序
{
unsigned char n;
for(;t>0;t--)
for(n=40;n>0;n--);
}
unsigned char pow(unsigned char n,unsigned char m)//n的m次方函數(shù)
{
unsigned char t,result=1;
for(t=0;t<m;t++){result=n*result;}
return result;
}
void init_1602()
{
e = 0; //1602初始化
write_com (0x38);
write_com (0x0c);
write_com (0x06);
write_com (0x01);
gd();
}
/*1602液晶代碼部分 ------------------------------ */
void write_com (uchar com) //寫命令
{
rs = 0;
rw = 0;
P0 = com;
delay (5);
e = 1;
delay (5);
e = 0;
}
void write_data (uchar dat) //寫數(shù)據(jù)
{
rs = 1;
rw = 0;
P0 = dat;
delay (5);
e = 1;
delay (5);
e = 0;
}
void gd() //液晶固定部分顯示
{
write_com(0x80);
for(num=0;num<8;num++)
{
write_data(table1[num]);
delay(5);
}
write_com(0x80+0x40);
for(num=0;num<10;num++)
{
write_data(table2[num]);
delay(5);
}
}
uchar receive(void)//接收處理函數(shù)
{
unsigned char guid=0,result[12],i,key=0,res=0,t,time=0;
while(1)//捕獲前導(dǎo)命令
{
while(DATA==1){t++;if(t>=90){delay1(100);return 0;}}//防止錯誤數(shù)據(jù)導(dǎo)致的死循環(huán)
if(t>=60&&t<95){t=0;key++;time=0;if(key>3)break;}//獲得前導(dǎo)命令跳出循環(huán),清除計時信號
else if(time>100){delay1(100);return 0;}//長0,錯誤信號返回0
else {t=0;time++;}//計時壘加,清除t
}
t=0;
time=0;
for(i=1;i<13;) //校驗碼及數(shù)據(jù)的接收共12位數(shù)據(jù)
{
while(DATA==1){t++;if(t>=95){delay1(100);return 0;}}//防止錯誤信號導(dǎo)致的死循環(huán)
if(t>=60&&t<95){t=0;i=1;time=0;}//去除多余的前導(dǎo)命令
else if(t>=28&&t<60){result[i-1]=1;i++;time=0;}//捕獲數(shù)據(jù)1
else if(t>0&&t<27){result[i-1]=0;i++;time=0;}//捕獲數(shù)據(jù)0
if(time>100)return 0; //消除長0的干擾確保數(shù)據(jù)正確
t=0; //清零
time++;//計時
}
if(result[0]==1&&result[1]==0&&result[2]==1&&result[3]==0)//判斷校驗碼
for(i=0;i<8;i++){res+=pow(2,i)*result[11-i];}//將結(jié)果轉(zhuǎn)換為十進(jìn)制數(shù)據(jù)
return res;//返回得到的結(jié)果
}
void display(uchar dat) //液晶數(shù)據(jù)顯示
{
uchar a,b;
a=dat/16;
b=dat%16;
if(a>9)
a=a+0;
if(b>9)
b=b+0;
write_com(0x80+0x4A);
write_data(table[a]);delay(5);
write_data(table[b]);delay(5);
}
void main()
{
init_1602(); //1602初始化
while(1)
{
dat=receive();
if(dat) //顯示
{
write_com(0x80+0x08);
write_data('O');delay(5);
write_data('K');delay(5);
write_data('!');delay(5);
display(dat);
}
else
{
write_com(0x80+0x08);
write_data('N');delay(5);
write_data('O');delay(5);
write_data('!');delay(5);
write_com(0x80+0x4A);
write_data(' ');delay(5);
write_data(' ');delay(5);
}
}
} |
|