清空串口的缓存及应用

PurgeComm(hCom, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR);

Read(int len)
{
 BOOL rtn = TRUE;
 iRecvLen = len;
 DWORD dwAllRecv = 0;
 memset(szRecv,0,sizeof(szRecv));
 int Count =0;
 while(TRUE)
 {
  Count++;
  DWORD len1 = 0;
  OVERLAPPED overread;
  
  //overread.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  
  DWORD dwBytesRead=len;
  COMSTAT ComStat;
  DWORD dwErrorFlags;
  
  memset(&overread,0,sizeof(overread));
  
  if(!ClearCommError(hCom,&dwErrorFlags,&ComStat))
  {
   PurgeComm(hCom, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR);
   rtn = FALSE;
   break;
  }
  
  dwBytesRead=min(dwBytesRead,(DWORD)ComStat.cbInQue);

  if(dwBytesRead == 0)
  {
   if(Count > 100)
   {
    rtn = FALSE;
    break;
   }
   else
   {
    Sleep(5);
    continue;
   }
   
  } 
  len1 = 0;
  BOOL bSucess = ::ReadFile(hCom,szRecv+dwAllRecv,dwBytesRead,&len1,&overread);
  if(!bSucess)
  {
   if(GetLastError() == ERROR_IO_PENDING)
   {
    if(GetOverlappedResult(hCom,&overread,&len1,TRUE))
    {
     rtn = TRUE;
     dwAllRecv += len1;
    }
    else
    {
     rtn = FALSE;
     break;
    }
   }
   else
   {
    rtn = FALSE;
    break;;

   }
  }
  else
  {
   rtn = TRUE;
   dwAllRecv += len1;
  }

  if(dwAllRecv == len)
  {
   rtn = TRUE;
   break;
  }
  Sleep(5);
 }
 
 
 return rtn; 
}

BOOL Write(char *pSend,DWORD len)
{
// return FALSE;
 if(hCom == INVALID_HANDLE_VALUE)
  return FALSE;
 DWORD len1 = 0;

 COMSTAT ComStat;
 DWORD dwErrorFlags;
 OVERLAPPED overwrite;
 memset(&overwrite,0,sizeof(overwrite));
 BOOL rtn = TRUE;
 PurgeComm(hCom, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR);
 if(!ClearCommError(hCom,&dwErrorFlags,&ComStat))
 {
  DWORD Code = GetLastError();
  PurgeComm(hCom, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR);
  rtn = FALSE;
  return rtn;
 }

 len1 = 0;
 BOOL bSucess = ::WriteFile(hCom,pSend,len,&len1,&overwrite);

 DWORD written = 0;
 DWORD n = 0;
 if(!bSucess)
 {
  if(GetLastError() == ERROR_IO_PENDING)
  {
   if(GetOverlappedResult(hCom,&overwrite,&len1,TRUE))
   {
    rtn = TRUE;
   }
   else
   {
    rtn = FALSE;
   }
  }
  else
  {
   rtn = FALSE;
  }
 }
 else
 {
  rtn = TRUE;
 }

 return rtn;
}

你可能感兴趣的:(个人心得,c++,串口通信)