while (TRUE)
{
DWORD dwError;
DWORD dwWantRead = 16;
DWORD dwRealRead = 0;
unsigned char pReadBuf[16] = {0};
if (ClearCommError(m_hCom,&dwError,NULL)){
PurgeComm(m_hCom,PURGE_TXABORT|PURGE_TXCLEAR);
//printf("PurgeComm ok!\n");
}
BOOL bReadStatus = FALSE;
bReadStatus = ReadFile(m_hCom,pReadBuf,dwWantRead,&dwRealRead,&wrOverlapped);
if (!bReadStatus){
dwError = GetLastError();
printf("%d\n",dwError);
if ( dwError == ERROR_IO_PENDING){
while(GetOverlappedResult(m_hCom,&wrOverlapped,&dwRealRead,FALSE)){
printf("dwRealRead = %d\n",dwRealRead);
}
}
}
//ReadFile(m_hCom,pReadBuf,dwWantRead,&dwRealRead,NULL);
/*发送数据*/
if (dwRealRead == 12 && pReadBuf[0] == 0x18 && pReadBuf[1] == 0xDB && pReadBuf[2] ==0x33 && pReadBuf[3] == 0xF1)
{
ResponseToECU(pReadBuf,m_hCom,wrOverlapped);
}
Sleep(100);
}
3 个解决方案
#1
DWORD Serial::Read(void* lpBuf, UINT nCount)
{
DWORD dwByteRead = 0;
if (m_hCommDevice == NULL)
{
TRACE(_T("'CSerial::Read': NULL handle !"));
ASSERT(FALSE);
return 0;
}
if (!ReadFile(m_hCommDevice, lpBuf, nCount, &dwByteRead, NULL))
{
/*
if (GetLastError() == ERROR_HANDLE_EOF)
AfxThrowSerialCommException(COXSerialCommException::rxTimeout, m_strFileName);
else {
COMSTAT comstat;
AfxThrowSerialCommException(GetCommException(comstat), m_strFileName);
}
*/
dwByteRead = 0;
}
// TRACE( "Read %d bytes %02x!!\n",dwByteRead,*(unsigned char *)lpBuf );
return dwByteRead;
}
#2
你这个是同步操作,但是异步操作的时候readfile没有读到字节 dwByteRead就直接赋值成0了。
#3
顶下 那个高人解答下
#1
DWORD Serial::Read(void* lpBuf, UINT nCount)
{
DWORD dwByteRead = 0;
if (m_hCommDevice == NULL)
{
TRACE(_T("'CSerial::Read': NULL handle !"));
ASSERT(FALSE);
return 0;
}
if (!ReadFile(m_hCommDevice, lpBuf, nCount, &dwByteRead, NULL))
{
/*
if (GetLastError() == ERROR_HANDLE_EOF)
AfxThrowSerialCommException(COXSerialCommException::rxTimeout, m_strFileName);
else {
COMSTAT comstat;
AfxThrowSerialCommException(GetCommException(comstat), m_strFileName);
}
*/
dwByteRead = 0;
}
// TRACE( "Read %d bytes %02x!!\n",dwByteRead,*(unsigned char *)lpBuf );
return dwByteRead;
}
#2
你这个是同步操作,但是异步操作的时候readfile没有读到字节 dwByteRead就直接赋值成0了。
#3
顶下 那个高人解答下