设为首页 加入收藏

TOP

13.6.8 写串口函数的实现
2013-10-07 14:37:25 来源: 作者: 【 】 浏览:59
Tags:13.6.8 串口 函数 实现

13.6.8  写串口函数的实现

写串口函数WriteChar()负责向串口输出数据,实现如下:

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

【代码解析】

WriteChar()函数的处理过程和读串口函数的处理过程及其相似,可以参考读串口函数。


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇13.6.9 数据发送函数的实现 下一篇13.6.6 串口关闭函数的实现

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: