最近研究了一下MFC下对串口的操作,测试了一下对设备的读写。
1.打开串口
1 GetDlgItem(IDC_BUTTON_OPEN)->EnableWindow(FALSE); 2 m_hComm = CreateFile("COM1", 3 GENERIC_READ | GENERIC_WRITE, 4 0, 5 NULL, 6 OPEN_EXISTING, 7 0, 8 NULL); 9 if (m_hComm == INVALID_HANDLE_VALUE) 10 { 11 TCHAR szBuf[1024]; 12 wsprintf(szBuf,_T("打开COM1失败,代码:%d"),GetLastError()); 13 return; 14 }
2.设置串口通讯参数
1 DCB dcb; 2 memset(&dcb,0,sizeof(dcb)); 3 if (!::GetCommState(m_hComm,&dcb)) 4 { 5 return; 6 } 7 dcb.BaudRate = 9600; 8 dcb.fParity = 1; 9 dcb.Parity = 0; 10 dcb.ByteSize = 8; 11 dcb.StopBits = 0; 12 SetCommState(m_hComm,&dcb); 13 14 if (!::SetupComm(m_hComm,1024,1024)) 15 { 16 return; 17 }
3.设定超时
1 //设定读超时 2 m_CommTimeOuts.ReadIntervalTimeout=MAXDWORD; 3 m_CommTimeOuts.ReadTotalTimeoutMultiplier=0; 4 m_CommTimeOuts.ReadTotalTimeoutConstant=0; 5 //在读一次输入缓冲区的内容后读操作就立即返回, 6 //而不管是否读入了要求的字符。 7 //设定写超时 8 m_CommTimeOuts.WriteTotalTimeoutMultiplier=100; 9 m_CommTimeOuts.WriteTotalTimeoutConstant=500; 10 ::SetCommTimeouts(m_hComm,&(m_CommTimeOuts)); //设置超时 11 ::PurgeComm(m_hComm,PURGE_RXCLEAR | PURGE_TXABORT);
4.开一个线程
1 m_pScanThread = AfxBeginThread(ScanThreadProc,this);
5.设置定时器
快捷键Ctrl+W在MessageMaps添加消息响应
1 void CTestDAMDADlg::OnTimer(UINT nIDEvent) 2 { 3 // TODO: Add your message handler code here and/or call default 4 //AfxMessageBox("Begin"); 5 switch (nIDEvent) 6 { 7 case TIMER_2: 8 { 9 //AfxMessageBox("Begin"); 10 OnButton2v(); 11 WriteComm(LENID,offlen); 12 KillTimer(TIMER_2); 13 SetTimer(TIMER_4,5000,NULL); 14 break; 15 } 16 case TIMER_4: 17 { 18 OnButton4v(); 19 WriteComm(LENID,offlen); 20 KillTimer(TIMER_4); 21 SetTimer(TIMER_6,5000,NULL); 22 break; 23 } 24 case TIMER_6: 25 { 26 OnButton6v(); 27 WriteComm(LENID,offlen); 28 KillTimer(TIMER_6); 29 SetTimer(TIMER_8,5000,NULL); 30 break; 31 } 32 33 case TIMER_8: 34 { 35 OnButton8v(); 36 WriteComm(LENID,offlen); 37 KillTimer(TIMER_8); 38 SetTimer(TIMER_10,5000,NULL); 39 break; 40 } 41 case TIMER_10: 42 { 43 OnButton10v(); 44 WriteComm(LENID,offlen); 45 KillTimer(TIMER_10); 46 SetTimer(TIMER_2,5000,NULL); 47 break; 48 } 49 50 default: 51 { 52 OnButton6v(); 53 WriteComm(LENID,offlen); 54 KillTimer(TIMER_2); 55 SetTimer(TIMER_4,5000,NULL); 56 break; 57 } 58 } 59 CDialog::OnTimer(nIDEvent); 60 }
线程里开启定时器
1 dlg->SetTimer(TIMER_2,5000,NULL);
6.调用写串口操作
1 BOOL CTestDAMDADlg::WriteComm(BYTE *lpByte,DWORD dwBytes) 2 { 3 DWORD dwBytesWrite = 20; 4 COMSTAT ComStat; 5 DWORD dwErrorFlags; 6 BOOL bWriteStat; 7 ClearCommError(m_hComm,&(dwErrorFlags),&(ComStat)); 8 bWriteStat = WriteFile(m_hComm,lpByte,dwBytes, 9 &dwBytesWrite,NULL); 10 if (!bWriteStat) 11 { 12 return FALSE; 13 } 14 else 15 { 16 return TRUE; 17 } 18 }
读串口操作类似,这样就完成了定时对串口的读写操作,测试通过!