windows下可以通過(guò)調(diào)用ClearCommError來(lái)獲取接收的串口數(shù)據(jù)的長(zhǎng)度。
代碼如下:
UINT GetDataSize(){ DWord dwError = 0; COMSTAT comstat; memset(&comstat, 0, sizeof(COMSTAT)); UINT size = 0; if (ClearCommError(m_hCom, &dwError, &comstat)) { size = comstat.cbInQue; } return size;}但是通過(guò)ClearCommError獲取到的并不一定是正確的數(shù)據(jù)長(zhǎng)度,因?yàn)樵谀阏{(diào)用此函數(shù)時(shí),數(shù)據(jù)不一定接收完成,所以在多次調(diào)用函數(shù)獲得的返回值不變時(shí),才能保證數(shù)據(jù)長(zhǎng)度的真確。
下面修改為阻塞型(有數(shù)據(jù)函數(shù)才會(huì)返回):
UINT GetDataSize(){ DWORD dwError = 0; COMSTAT comstat; memset(&comstat, 0, sizeof(COMSTAT)); UINT size = 0; while (size == 0) { if (ClearCommError(m_hCom, &dwError, &comstat)) { size = comstat.cbInQue; } } Sleep(3); UINT newSize= 0; if (ClearCommError(m_hCom, &dwError, &comstat)) { newSize= comstat.cbInQue; } while (newSize!= size) { size = newSize; Sleep(3); if (ClearCommError(m_hCom, &dwError, &comstat)) { newSize= comstat.cbInQue; } } return newSize;}新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注