13.6.8 写串口函数的实现
写串口函数WriteChar()负责向串口输出数据,实现如下:
- 01 void CMySerial::WriteChar(CMySerial* port)
- 02 {
- 03 BOOL bWrite = TRUE;
- 04 BOOL bResult = TRUE;
- 05 DWORD BytesSent = 0;
- 06 ResetEvent(port->m_hWriteEvent);
- 07 //锁定临界资源
- 08 EnterCriticalSection(&port->m_csCommunicationSync);
- 09 if (bWrite)
- 10 {
- 11 port->m_ov.Offset = 0;
- 12 port->m_ov.OffsetHigh = 0;
- 13 //清空串口缓冲
- 14 PurgeComm(port->m_hComm,
- 15 PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT |
- 16 PURGE_TXABORT);
- 17
- 18 bResult = WriteFile(port->m_hComm, port->m_szWriteBuffer,
- 19 strlen((char*)port->m_szWriteBuffer),
- port->m_nWriteSize,
- 20 &BytesSent, &port->m_ov); //向串口输出数据
- 21 if (!bResult)
- 22 { //写串口失败
- 23 DWORD dwError = GetLastError();
- 24 switch (dwError)
- 25 {
- 26 case ERROR_IO_PENDING:
- 27 { //尚未写完数据
- 28 BytesSent = 0;
- 29 bWrite = FALSE;
- 30 break;
- 31 }
- 32 default:
- 33 { //错误信息提示
- 34 port->ProcessErrorMessage("WriteFile()");
- 35 }
- 36 }
- 37 }
- 38 else
- 39 { //解锁临界资源
- 40 LeaveCriticalSection(&port->m_csCommunicationSync);
- 41 }
- 42 }
- 43 if (!bWrite)
- 44 {
- 45 bWrite = TRUE;
- 46 //等待写动作完成
- 47 bResult = GetOverlappedResult(port->m_hComm, &port->m_ov,
- 48 &BytesSent, TRUE);
- 49 LeaveCriticalSection(&port->m_csCommunicationSync);
- 50 if (!bResult)
- 51 {
- 52 port->ProcessErrorMessage("GetOverlappedResults() in WriteFile()");
- 53 }
- 54 }
- 55 //发送失败
- 56 if (BytesSent != port->m_nWriteSize)
- 57 {
- 58 TRACE("WARNING: WriteFile() error.. Bytes Sent: %d; Message 59 Length: %d\n", BytesSent, strlen((char*)port->m_szWriteBuffer));
- 60 }
- 61 }
【代码解析】
WriteChar()函数的处理过程和读串口函数的处理过程及其相似,可以参考读串口函数。