MODBUS通訊協(xié)議解析及編碼例程
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校驗(yàn)碼計(jì)算
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;
}
}
(三)、數(shù)據(jù)發(fā)送
zxaddr=11;//讀取地址為11的巡檢表數(shù)據(jù)
zxnum=10;//讀取十個(gè)通道的數(shù)據(jù)
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);
(四)、數(shù)據(jù)讀取
ReadFile(hCom,writebuf,5+zxnum*2,comnum,NULL);//讀取zxnum個(gè)通道數(shù)據(jù)
可增加錯(cuò)誤處理程序,如地址碼錯(cuò)誤、CRC碼錯(cuò)誤判斷、通訊故障處理等。本文引用地址:http://www.ex-cimer.com/article/155083.htm
pa相關(guān)文章:pa是什么
通信相關(guān)文章:通信原理
評論