请教串口发送数据发送不完全的问题
小弟在使用串口进行通讯的时候,发现有时候会出现发送数据不全的情况(比如我的命令有11个字符,它只发送4个),特别是主机在进行视频播放等大数据量处理而比较忙的时候.这让我很痛苦,因为直接会导致接收数据的紊乱.
我的串口通讯是异步方式的,下面是往串口写数据的代码:
void CSerialPort::WriteChar(CSerialPort* port)
{
BOOL bWrite = TRUE;
BOOL bResult = TRUE;
DWORD BytesSent = 0;
ResetEvent(port->m_hWriteEvent);
// Gain ownership of the critical section
EnterCriticalSection(&port->m_csCommunicationSync);
if (bWrite)
{
// Initailize variables
port->m_ov.Offset = 0;
port->m_ov.OffsetHigh = 0;
// Clear buffer
PurgeComm(port->m_hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);
bResult = WriteFile(port->m_hComm, // Handle to COMM Port
port->m_szWriteBuffer,
// Pointer to message buffer in calling finction
(DWORD)port->m_nStringLength, // Length of message to send//strlen((char*)port->m_szWriteBuffer)
&BytesSent,// Where to store the number of bytes sent
&port->m_ov); // Overlapped structure
// deal with any error codes
if (!bResult)
{
DWORD dwError = GetLastError();
switch (dwError)
{
case ERROR_IO_PENDING:
{
// continue to GetOverlappedResults()
BytesSent = 0;
bWrite = FALSE;
break;
}
default:
{
// all other error codes
port->ProcessErrorMessage("WriteFile()");
}
}
}
else
{
LeaveCriticalSection(&port->m_csCommunicationSync);
}
} // end if(bWrite)
if (!bWrite)
{
bWrite = TRUE;
bResult = GetOverlappedResult( port->m_hComm, // Handle to COMM port
&port->m_ov, // Overlapped structure
&BytesSent, // Stores number of bytes sent
TRUE); // Wait flag
LeaveCriticalSection(&port->m_csCommunicationSync);
// deal with the error code
if (!bResult)
{
port->ProcessErrorMessage("GetOverlappedResults() in WriteFile()");
}
} // end if (!bWrite)
// flush the COM Port...this sends out any info still sitting in the buffer //add 11.05
EnterCriticalSection(&port->m_csCommunicationSync);
FlushFileBuffers( port->m_hComm );
LeaveCriticalSection(&port->m_csCommunicationSync);
// Verify that the data size send equals what we tried to send
if ( BytesSent != (DWORD)port->m_nStringLength )
{
TRACE("WARNING: WriteFile() error.. Bytes Sent: %d; Message Length: %d\n", BytesSent, strlen((char*)port->m_szWriteBuffer));
}
}
每次发生接收紊乱的时候trace窗都会显示WriteFile() error,各位大侠有没有什么好的解决方案