//2016-1-6
現象:每次打開串口只能發送壹次,需要關閉再打開或者接收完數據才能發送
成因:在自帶串口的電腦、或用優質的USB串口線都沒有出現改問題,很有可能跟串口線的質量有關,
調試發現在調用玩WriteToPort函數 SetEvent(m_hWriteEvent);後第壹次能夠正常進入監視線程(CommThread(LPVOID pParam))
調用WriteChar(port),然之後,壹直進入ReceiveChar(port, comstat),再次發送SetEvent(m_hWriteEvent)也無法去到WriteChar(port)。
分析:某種原因導致壹直存在串口接收消息,而(WaitForMultipleObjects)函數在等待事件具有優先級判斷,InitPort()函數中
m_hEventArray[1] = m_ov.hEvent; m_hEventArray[2] = m_hWriteEvent;m_ov.hEvent事件(包含接收事件),寫串口事件m_hWriteEvent;優先級更高
所以在出現壹直存在接收事件時,無法發送數據;
Event = WaitForMultipleObjects(3,port->m_hEventArray,FALSE,INFINITE);
解決:
解決的思路是將寫串口事件(m_hWriteEvent)的優先級高於接收事件(m_ov.hEvent),如下:
修改
BOOL CSerialPort::InitPort(......){
......
m_hEventArray[0] = m_hShutdownEvent; // highest priority
m_hEventArray[1] = m_hWriteEvent;
m_hEventArray[2] = m_ov.hEvent;
......
}
UINT CSerialPort::CommThread(LPVOID pParam){
......
switch (Event)
{
case 0:
{
......
}
case 2:
{
memset(&comstat, 0, sizeof(COMSTAT));
GetCommMask(port->m_hComm, &CommEvent);
if (CommEvent & EV_RXCHAR)//接收到字符,並置於輸入緩沖區中
// Receive character event from port.
ReceiveChar(port, comstat);
......
break;
}
case 1: /// write event發送數據
{
// Write character event from port
WriteChar(port);
break;
}
default:
{
......
}
......
}