(一)、通讯口设置
DCB dcb;
hCom=CreateFile("COM1",
GENERIC_READ|GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
NULL);
if(hCom==INVALID_HANDLE_VALUE)
{
MessageBox("createfile error,error");
}
BOOL error=SetupComm(hCom,1024,1024);
if(!error)
MessageBox("setupcomm error");
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校验码计算
UINT crc
void calccrc(BYTE crcbuf)
{
BYTE i;
crc=crc ^ crcbuf;
for(i=0;i<8;i++)
{
BYTE TT;
TT=crc&1;
crc=crc>>1;
crc=crc&0x7fff;
if (TT==1)
crc=crc^0xa001;
crc=crc&0xffff;
}
}
(三)、数据发送
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]=crc & 0xff;
writebuf2[7]=crc/0x100;
WriteFile(hCom,writebuf2,8,&comnum,NULL);
(四)、数据读取
ReadFile(hCom,writebuf,5+zxnum*2,&comnum,NULL);//读取zxnum个通道数据可增加错误处理程序,如地址码错误、CRC码错误判断、通讯故障处理等。
别外还有其他说明,请登陆聚英电子网--搜索--modbus rtu协议