69,373
社区成员
发帖
与我相关
我的任务
分享
static COMSTAT ms_ComStat; // 串口状态
static OVERLAPPED ms_Ov;
int Uart_Read(HANDLE hComm, unsigned char *rbuf, int *len)
{
BOOL bRead = TRUE;
BOOL bResult = TRUE;
DWORD dwError = 0;
DWORD BytesRead = 0;
int rtn = 0;
BYTE tmpbuf[256];
DWORD nPos = 0;
DWORD readcnt = 0; // 读到数据次数
memset(tmpbuf, 0x00, sizeof(256));
for(;;)
{
bResult = ClearCommError(hComm, &dwError, &ms_ComStat);
if ( ms_ComStat.cbInQue == 0 )
{
if( readcnt == 0 )
{
return -1;
}
else
{
memcpy(len, &nPos, sizeof(int));
printf("[Uart_Read]nPos is %d, readcnt is %d\r\n", nPos, readcnt);
return 0;
}
}
printf("[Uart_Read]cbInQue is %d\r\n", ms_ComStat.cbInQue);
if ( bRead )
{
bResult = ReadFile(hComm, // Handle to COMM port
tmpbuf, // RX Buffer Pointer
ms_ComStat.cbInQue, // Read one byte
&BytesRead, // Stores number of bytes read
NULL); // pointer to the m_ov structure
if ( !bResult )
{
rtn = -1;
switch (dwError = GetLastError())
{
case ERROR_IO_PENDING:
{
bRead = FALSE;
break;
}
default:
{
break;
}
}
}
else
{
bRead = TRUE;
readcnt++;
memcpy(&rbuf[nPos], tmpbuf, ms_ComStat.cbInQue);
nPos += ms_ComStat.cbInQue;
}
} // close if (bRead)
if ( !bRead )
{
bRead = TRUE;
bResult = GetOverlappedResult(hComm, // Handle to COMM port
&ms_Ov, // Overlapped structure
&BytesRead, // Stores number of bytes read
TRUE); // Wait flag
}
}
}
static HANDLE ms_hcomm = NULL;
int _tmain(int argc, _TCHAR* argv[])
{
int bufLen = 0;
unsigned char buf[256] = {0};
//wchar_t *cComName = _T("COM1");
char *cComName = "COM1";
Uart_Init();
ms_hcomm = Uart_Open((char *)cComName);
if( !Uart_IsOpen(ms_hcomm) )
{
if( !Uart_SetTimeout(ms_hcomm, MAXDWORD, 0, 0, 0, 0) )
{
printf("[_tmain] SetTimeout ok\r\n");
}
Uart_SetDcb(ms_hcomm, CBR_9600, EVENPARITY, ONESTOPBIT, 8);
//SetCommMask(ms_hcomm, EV_RXCHAR);//当有字符在inbuf中时产生这个事件
while(1)
{
if( !Uart_Read(ms_hcomm, buf, &bufLen) )
{
printf("buf addr is %08x, buflen is %d:", buf, bufLen);
for(int i=0; i<bufLen; i++)
{
printf("%02x ", buf[i]);
}
printf("\r\n");
}
Sleep(50);
}
}
return 0;
}
一次不能发多点吗
任何通讯机制,收方收得太慢都会导致发方发的速度受阻或发的数据丢失。