MODBUS通讯协议及编程
MessageBox(createfileerror,error);
}
BOOLerror=SetupComm(hCom,1024,1024);
if(!error)
MessageBox(setupcommerror);
error=GetCommState(hCom,dcb);
if(!error)
MessageBox(getcommstate,error);
dcb.BaudRate=2400;
dcb.ByteSize=8;
dcb.Parity=EVENPARITY;//NOPARITY;
dcb.StopBits=ONESTOPBIT;
error=SetCommState(hCom,dcb);
(二)、CRC校验码计算
UINTcrc
voidcalccrc(BYTEcrcbuf)
{
BYTEi;
crc=crc^crcbuf;
for(i=0;i8;i++)
{
BYTETT;
TT=crc1;
crc=crc>>1;
crc=crc0x7fff;
if(TT==1)
crc=crc^0xa001;
crc=crc0xffff;
}
}
(三)、数据发送
zxaddr=11;//读取地址为11的巡检表数据
zxnum=10;//读取十个通道的数据
writebuf2[0]=zxaddr;
writebuf2[1]=3;
writebuf2[2]=0;
writebuf2[3]=0;
writebuf2[4]=0;
writebuf2[5]=zxnum;
crc=0xffff;
calccrc(writebuf2[0]);
calccrc(writebuf2[1]);
calccrc(writebuf2[2]);
calccrc(writebuf2[3]);
calccrc(writebuf2[4]);
calccrc(writebuf2[5]);
writebuf2[6]=crc0xff;
writebuf2[7]=crc/0x100;
WriteFile(hCom,writebuf2,8,comnum,NULL);
(四)、数据读取
ReadFile(hCom,writebuf,5+zxnum*2,comnum,NULL);//读取zxnum个通道数据
可增加错误处理程序,如地址码错误、CRC码错误判断、通讯故障处理等。本文引用地址://m.amcfsurvey.com/article/157224.htm
评论