MFC下对串口的操作以及定时器的调用

最近研究了一下MFC下对串口的操作,测试了一下对设备的读写。

1.打开串口

     GetDlgItem(IDC_BUTTON_OPEN)->EnableWindow(FALSE);
m_hComm = CreateFile("COM1",
GENERIC_READ | GENERIC_WRITE,
,
NULL,
OPEN_EXISTING,
,
NULL);
if (m_hComm == INVALID_HANDLE_VALUE)
{
TCHAR szBuf[];
wsprintf(szBuf,_T("打开COM1失败,代码:%d"),GetLastError());
return;
}

2.设置串口通讯参数

 DCB dcb;
memset(&dcb,,sizeof(dcb));
if (!::GetCommState(m_hComm,&dcb))
{
return;
}
dcb.BaudRate = ;
dcb.fParity = ;
dcb.Parity = ;
dcb.ByteSize = ;
dcb.StopBits = ;
SetCommState(m_hComm,&dcb); if (!::SetupComm(m_hComm,,))
{
return;
}

3.设定超时

                    //设定读超时
m_CommTimeOuts.ReadIntervalTimeout=MAXDWORD;
m_CommTimeOuts.ReadTotalTimeoutMultiplier=;
m_CommTimeOuts.ReadTotalTimeoutConstant=;
//在读一次输入缓冲区的内容后读操作就立即返回,
//而不管是否读入了要求的字符。
//设定写超时
m_CommTimeOuts.WriteTotalTimeoutMultiplier=;
m_CommTimeOuts.WriteTotalTimeoutConstant=;
::SetCommTimeouts(m_hComm,&(m_CommTimeOuts)); //设置超时
::PurgeComm(m_hComm,PURGE_RXCLEAR | PURGE_TXABORT);

4.开一个线程
  m_pScanThread = AfxBeginThread(ScanThreadProc,this);

5.设置定时器

快捷键Ctrl+W在MessageMaps添加消息响应

 void CTestDAMDADlg::OnTimer(UINT nIDEvent)
{
// TODO: Add your message handler code here and/or call default
//AfxMessageBox("Begin");
switch (nIDEvent)
{
case TIMER_2:
{
//AfxMessageBox("Begin");
OnButton2v();
WriteComm(LENID,offlen);
KillTimer(TIMER_2);
SetTimer(TIMER_4,,NULL);
break;
}
case TIMER_4:
{
OnButton4v();
WriteComm(LENID,offlen);
KillTimer(TIMER_4);
SetTimer(TIMER_6,,NULL);
break;
}
case TIMER_6:
{
OnButton6v();
WriteComm(LENID,offlen);
KillTimer(TIMER_6);
SetTimer(TIMER_8,,NULL);
break;
} case TIMER_8:
{
OnButton8v();
WriteComm(LENID,offlen);
KillTimer(TIMER_8);
SetTimer(TIMER_10,,NULL);
break;
}
case TIMER_10:
{
OnButton10v();
WriteComm(LENID,offlen);
KillTimer(TIMER_10);
SetTimer(TIMER_2,,NULL);
break;
} default:
{
OnButton6v();
WriteComm(LENID,offlen);
KillTimer(TIMER_2);
SetTimer(TIMER_4,,NULL);
break;
}
}
CDialog::OnTimer(nIDEvent);
}

线程里开启定时器
  dlg->SetTimer(TIMER_2,,NULL);

6.调用写串口操作

 BOOL CTestDAMDADlg::WriteComm(BYTE *lpByte,DWORD dwBytes)
{
DWORD dwBytesWrite = ;
COMSTAT ComStat;
DWORD dwErrorFlags;
BOOL bWriteStat;
ClearCommError(m_hComm,&(dwErrorFlags),&(ComStat));
bWriteStat = WriteFile(m_hComm,lpByte,dwBytes,
&dwBytesWrite,NULL);
if (!bWriteStat)
{
return FALSE;
}
else
{
return TRUE;
}
}

读串口操作类似,这样就完成了定时对串口的读写操作,测试通过!

上一篇:Java基础-Java中的并法库之线程池技术


下一篇:GNOME Shell叫板Ubuntu Unity:优劣PK