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校驗碼計算
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;//讀取十個通道的數(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個通道數(shù)據(jù)
可增加錯誤處理程序,如地址碼錯誤、CRC碼錯誤判斷、通訊故障處理等。本文引用地址:http://m.butianyuan.cn/article/157224.htm
評論