我想编一个串口程序程序开始我先开一个线程,在线程里用WaitCommEvent()等待串口事件的发生代码如下:
UINT CommProc(LPVOID pParam)
{
CUartDlg *pDlg = (CUartDlg *)pParam; DWORD dwMask = 0;
OVERLAPPED os;


os.hEvent = CreateEvent(NULL, TRUE,FALSE,NULL);

SetCommMask(pDlg->hCom,EV_CTS|EV_DSR|EV_RING|EV_RLSD|EV_RXCHAR|EV_TXEMPTY);
SetCommMask(pDlg->hCom, EV_CTS); while (true) 
{
if (WaitCommEvent(pDlg->hCom, &dwMask, &os)) 
{
if (dwMask & EV_CTS) //CTS变化
{}
if (dwMask & EV_DSR) //DSR变化
{}
if (dwMask & EV_RING) //ring信号变化
{}
if (dwMask & EV_RLSD) //CD信号变化
{}
if (dwMask & EV_RXCHAR) //输入缓冲区收到新字符
{}
if (dwMask & EV_TXEMPTY) //发送缓冲区空
{}
}

else//出错处理
{
                       dwError = GetLastError();
                       if( dwError == ERROR_IO_PENDING)
                       {
                          //程序总是跳到这里
                       }
}

}
return 0;
}可是不知道为什么,只要程序一运行,我没有作任何串口操作,WaitCommEvent()就会返回false,不知为什么串口使用重叠方式打开的
hCom = CreateFile("COM1",GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,NULL);

解决方案 »

  1.   

    SetCommMask(pDlg->hCom,EV_CTS|EV_DSR|EV_RING|EV_RLSD|EV_RXCHAR|EV_TXEMPTY);
    SetCommMask(pDlg->hCom, EV_CTS);
    ????????????????????????????????????????????????
      

  2.   

    哦,对不起,
    SetCommMask(pDlg->hCom,EV_CTS|EV_DSR|EV_RING|EV_RLSD|EV_RXCHAR|EV_TXEMPTY);
    //SetCommMask(pDlg->hCom, EV_CTS); 这一句我后来注释掉了,我想让程序等待串口的多个事件,但不知为什么WaitCommEvent(pDlg->hCom, &dwMask, &os)总是出错返回?
      

  3.   

    出错的代码就是 ERROR_IO_PENDING ,表示串口还有工作没有做完,但我之前并没有对串口进行操作
      

  4.   

    // Set the event mask.     fSuccess = SetCommMask(hCom, EV_CTS | EV_DSR);    if (!fSuccess) 
        {
            // Handle the error. 
            printf("SetCommMask failed with error %d.\n", GetLastError());
            return;
        }    // Create an event object for use by WaitCommEvent.     o.hEvent = CreateEvent(
            NULL,   // default security attributes 
            FALSE,  // auto reset event 
            FALSE,  // not signaled 
            NULL    // no name
    );
            // Intialize the rest of the OVERLAPPED structure to zero.
        o.Internal = 0;
        o.InternalHigh = 0;
        o.Offset = 0;
        o.OffsetHigh = 0;    assert(o.hEvent);    if (WaitCommEvent(hCom, &dwEvtMask, &o)) 
        {
            if (dwEvtMask & EV_DSR) 
            {
                 // To do.
            }        if (dwEvtMask & EV_CTS) 
            {
                // To do. 
            }
        }
        else
        {
            DWORD dwRet = GetLastError();
            if( ERROR_IO_PENDING == dwRet)
            {
                printf("I/O is pending...\n");            // To do.
            }
            else 
                printf("Wait failed with error %d.\n", GetLastError());
        }
    }