用ReadFile、WriteFile进行串口读写,设定读数据:有数据时读数据返回,没有数据最长等待1秒钟。
异步读取无法等待(我试了一下不行,如果有办法麻烦告知)
我采用的是同步读写。
main()
{
m_hCom = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL ); CommTimeOuts.ReadIntervalTimeout = 10;
CommTimeOuts.ReadTotalTimeoutMultiplier = 0;
CommTimeOuts.ReadTotalTimeoutConstant = 1000;//等待一秒
CommTimeOuts.WriteTotalTimeoutMultiplier = 0;
CommTimeOuts.WriteTotalTimeoutConstant = 5000; SetCommTimeouts( m_hCom, &CommTimeOuts ); dcb.DCBlength = sizeof( DCB );
GetCommState( m_hCom, &dcb );
dcb.BaudRate = 9600;
dcb.ByteSize = 8;
dcb.fParity = NOPARITY;
dcb.StopBits = ONESTOPBIT; SetCommState( m_hCom, &dcb );
SetupComm( m_hCom, 600, 600 ); memcpy(buffer,"\x12\x00\x05\x00\x12\x00\x00\x00\x05",9);
dwBytesWritten=9;
bWriteStat = WriteFile( m_hCom, buffer, dwBytesWritten, &dwBytesWritten, 0 );
if(!(bWriteStat))
AfxMessageBox("err"); dwNumberOfBytesToRead=100;
readsucess=ReadFile(m_hCom,buffer,BytesToRead,&BytesRead,NULL);
if(!(readsucess))
AfxMessageBox("err");
}
这样可以实现,但有一个问题,当不存在串口设备时,读数据等待一秒返回,再写数据时,writefile返回失败,只有重新运行程序才可以。为什么??怎么解决?〉

解决方案 »

  1.   

    在读写操作前现检查串口句柄:m_hCom是否合法,合法在读写操作。
    另外你的
    CommTimeOuts.WriteTotalTimeoutMultiplier = 0;
    CommTimeOuts.ReadTotalTimeoutMultiplier = 0;
    也很容易出问题,当你的数据很长的时候,就会出现读、写不全问题,就是末尾的数据丢了;
    建议你把这2个参数设置为你要读写的数据长度。