# 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写数据
void write_com (uchar com); //1602写命令
unsigned char pow(unsigned char n,unsigned char m); //n的m次方函数
uchar receive(void); //接收处理函数
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次方函数
{
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) //写数据
{
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)//接收处理函数
{
unsigned char guid=0,result[12],i,key=0,res=0,t,time=0;
while(1)//捕获前导命令
{
while(DATA==1){t++;if(t>=90){delay1(100);return 0;}}//防止错误数据导致的死循环
if(t>=60&&t<95){t=0;key++;time=0;if(key>3)break;}//获得前导命令跳出循环,清除计时信号
else if(time>100){delay1(100);return 0;}//长0,错误信号返回0
else {t=0;time++;}//计时垒加,清除t
}
t=0;
time=0;
for(i=1;i<13;) //校验码及数据的接收共12位数据
{
while(DATA==1){t++;if(t>=95){delay1(100);return 0;}}//防止错误信号导致的死循环
if(t>=60&&t<95){t=0;i=1;time=0;}//去除多余的前导命令
else if(t>=28&&t<60){result[i-1]=1;i++;time=0;}//捕获数据1
else if(t>0&&t<27){result[i-1]=0;i++;time=0;}//捕获数据0
if(time>100)return 0; //消除长0的干扰确保数据正确
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];}//将结果转换为十进制数据
return res;//返回得到的结果
}
|