程序使用了简单的协议,准确率较高!
欢迎高手指教!
C51程序设计:
#include <reg51.h>
#include <string.h>
//#include "HC595_Driver.h"
//**************** 55 01 XX YY ZZ CS(=55+01+XX+YY+ZZ) AA(EE)********************//
//****************校验 方向 3个数据 检验和 帧尾************************************//
//
#define INBUF_LEN 3 //数据长度
unsigned char buff[INBUF_LEN];
unsigned char flag,Res=0;
sbit RS485E=P3^6; //定义485的使能脚
void init_serialcomm(void)
{
SCON = 0x50; //SCON: serail mode 1, 8-bit UART, enable ucvr
TMOD |= 0x20; //TMOD: timer 1, mode 2, 8-bit reload
PCON |= 0x80; //SMOD=1;
TH1 = 0xF3; //Baud:4800 fosc=12MHz
TL1 = 0xF3;
TR1 = 1; // timer 1 run
ES=1; //Enable Serial Interrupt
TI=0;
RS485E=0; //485发送使能端,使能接受
EA=1;
}
//向串口发送一个字符
void send_char_com(unsigned char Sendch)
{
RS485E=1; //485的使能发送
SBUF=Sendch;
while(!TI);
TI=0;
RS485E=0; //485的使能接受
}
void sendStrings(char *dat)
{
while(*dat!='\0')
{
send_char_com(*dat++);
}
}
unsigned char Check_Data(unsigned char dat)
{
static unsigned char FCMS=0,cnt=0,dir,cs;
switch (FCMS)
{
case 0:
{
if(dat==0x55) //找到帧头
{
FCMS=1;
cnt=0;
}
break;
}
case 1:
{
dir=dat; //保存方向
FCMS=2;
break;
}
case 2:
{
buff[cnt++]=dat; //接收数据(3个数据)
if(cnt>=3)
{
FCMS=3;
}
break;
}
case 3:
{
cs=dat; //保存校验
FCMS=4;
break;
}
case 4:
{
if(dat==0xAA) //接受一帧数据完毕
{
flag=1;
if(cs==(0x55+dir+buff[0]+buff[1]+buff[2])) //帧校验正确
{
if(dir==0x01) //方向正确
{
Res=1;//数据帧OK
FCMS=0; //重置状态
break;
}
}
Res=0;//数据帧错误
FCMS=0;
}
else
{
FCMS=0;
}
break;
}
default: FCMS=0;
break;
}
return 1;
}
//串口接收中断函数
void serial () interrupt 4
{
unsigned char dat;
if(RI)
{
dat=SBUF;
RI=0;
Check_Data(dat);
}
else
{
TI=0;
}
}
void main()
{
init_serialcomm(); //初始化串口
sendStrings("hello world!\r\n");
while(1)
{
if(flag)
{
if(Res)
{
send_char_com(0xFF);
}else
{
send_char_com(0x00);
}
flag=0;
}
}
}