使用WinAPI读取串口偶尔读不到数据
代码如下,这段代码是在一个单独的线程里的。问题是有的时候发同样的命令在WaitCommEvent时可以等到EV_RXCHAR,有的时候不能(等到的是另一个EV_TXEMPTY),关掉程序等一会儿就又能够读了。
try
{
DWORD dwEvtMask = 0;
OVERLAPPED os;
memset(&os, 0, sizeof(OVERLAPPED));
//os.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
SetCommMask(hCom, EV_RXCHAR|EV_TXEMPTY);
for (;;)//Dead loop to receive all serial events.
{
WaitCommEvent(hCom, &dwEvtMask, &os);
if ((dwEvtMask & EV_RXCHAR) == EV_RXCHAR)
{
COMSTAT comStat;
DWORD dwLength;
DWORD dwErrorFlags;
ClearCommError(hCom, &dwErrorFlags, &comStat);
dwLength = comStat.cbInQue;
if (dwLength > 0)
{
QSCRcvCmd rcvCmd;
BOOL fReadStat;
BYTE buffer[1024] = {0};
DWORD dwBytesRead;
fReadStat = ReadFile(hCom, &buffer, dwLength, &dwBytesRead, &os);
if (!fReadStat)
{
if (GetLastError() == ERROR_IO_PENDING)
{
DWORD dwError;
while (!GetOverlappedResult(hCom, &os, &dwBytesRead, TRUE))
{
dwError = GetLastError();
if (dwError == ERROR_IO_INCOMPLETE)
continue;
}
}
}
CQSCDlg::AnalyseRcvCmd(buffer, dwLength, &rcvCmd, hDlg);
memset(buffer, 0, 1024);
}
}
}
}
catch (...)
{
}