程序代码是这样的:
#include <stc12c5a60s2.h>
unsigned char xdata rsbuf[64];//定义接收数据数组
unsigned char ryb;//接收数据游标
unsigned char length;//接收到数据的总长度
unsigned char xdata tsbuf[64];//ASCII转换成Hex后存储数组
unsigned char xdata ssbuf[64];//校验成功发送数组
unsigned char check;
bit check_true=0;
void Modbus_Init(unsigned char aa,unsigned char *bb,unsigned char *cc);
void PrintStirng(unsigned char *puts);
void Delay_90us(void);
void send(unsigned char temp);
sbit led0=P0^6;
sbit led1=P0^7;
sbit RX=P3^0;
sbit TX=P3^1;
void send(unsigned char temp)
{
SBUF=temp;
while(!TI);
}
void Delay_90us()
{
unsigned char i, j;
i = 2;
j = 15;
do
{
while (--j);
} while (--i);
}
void PrintString(unsigned char *puts)
{
for(;*puts !=0;puts++)
{
SBUF=*puts;
while(!TI);
Delay_90us();
}
}
void Modbus_Init(unsigned char aa,unsigned char *bb,unsigned char *cc)
{
unsigned char i,t;
for(i=1;i<=(aa-3);i++)
{
if((bb>=0x30)&&(bb<=0x39))
{
if(i%2)
{bb=(bb-0x30)<<4;}
else
{bb=bb-0x30;}
}
else if((bb>=0x41)&&(bb<=0x46))
{
if(i%2)
{bb=(bb-0x37)<<4;}
else
{bb=bb-0x37;}
}
else if((bb>=0x61)&&(bb<=0x66))
{
if(i%2)
{bb=(bb-0x47)<<4;}
else
{bb=bb-0x47;}
}
}
t=0;
for(i=1;i<=(aa-3);i=i+2)
{
if(t<=((aa-5)>>1))
{
cc[t]=bb+bb[i+1];
t++;
}
else
{t=0;}
}
for(t=0;t<=((aa-7)>>1);t++)
{
check +=cc[t];
}
check=0x100-check;
if(check==cc[(aa-5)>>1])
{
check_true=1;
}
else
{
check_true=0;
}
}
void main()
{
PCON |= 0x80; //使能波特率倍速位SMOD
SCON = 0x50; //8位数据,可变波特率
AUXR |= 0x04; //独立波特率发生器时钟为Fosc,即1T
BRT = 0xFA; //设定独立波特率发生器重装值
AUXR |= 0x01; //串口1选择独立波特率发生器为波特率发生器
AUXR |= 0x10; //启动独立波特率发生器
ES=1;
EA=1;
while(1)
{
if(check_true)
{
Delay_90us();
check_true=0;
PrintString((unsigned char *)ssbuf);
}
}
}
void Serical_Interrupt() interrupt 4
{
unsigned char temp,temp_next;
unsigned char i;
if(RI)
{
RI=0;
temp=SBUF;
rsbuf[ryb]=temp;
ryb++;
if((rsbuf[0]==':')&&(temp==0x0A)&&(temp_next==0x0D))
{
length=ryb;
ryb=0;
for(i=0;i<=sizeof(rsbuf);i++)
{
ssbuf=rsbuf;
}
Modbus_Init(length,(unsigned char *)rsbuf,(unsigned char *)tsbuf);
send(check);
}
temp_next=temp;
}
if(TI)
{
TI=0;
}
}
问题是这样的:
通过串口助手发送“:0123456789A7\r\n”。第一次发送该字符串是校验是成功的也有返回,但是发送第二次时校验不成功而且校验值为0x00。第三次发送时校验再次成功,但是第四次校验值又为0x00;以后都是一次类推。这是个什么情况。难道是我的MODBUS解析函数有问题?太奇怪了。
|