vs2013 串口收发例程
vs2013 串口收发例程讲解:
- 创建MFC对话框,并布局好控件,后加入串口控件(在对话框上右键,选择“insert ActiveX Control...”,之选择“Microsoft Communications Control, version 6.0”控件)。
- 添加串口控件事件处理函数(右键串口控件,选择"Add Event Handler"),同时添加串口成员变量,以及编辑框成员变量
- 同时双击两个按键,添加两个按键事件处理函数(一个处理串口打开,一个处理串口关闭)。
- 事件代码如下:
- 开启串口按键事件处理:
-
1 void CSerialComDlg::OnBnClickedButton1()//open 2 { 3 // TODO: Add your control notification handler code here 4 if (m_pcomm.get_PortOpen()) 5 { 6 m_pcomm.put_PortOpen(false); 7 } 8 m_pcomm.put_Settings(_T("9600,n,8,1")); 9 m_pcomm.put_InputMode(1); 10 m_pcomm.put_RThreshold(8); 11 m_pcomm.put_InputLen(0); 12 m_pcomm.put_PortOpen(true); 13 if (m_pcomm.get_PortOpen()) 14 { 15 GetDlgItem(IDC_BUTTON1)->ShowWindow(SW_HIDE); 16 GetDlgItem(IDC_BUTTON2)->ShowWindow(SW_SHOW); 17 } 18 else 19 { 20 AfxMessageBox(_T("Can not open serial port.")); 21 } 22 m_pcomm.get_Input(); 23 }
- 关闭串口按键事件处理:
1 void CSerialComDlg::OnBnClickedButton2()//close 2 { 3 // TODO: Add your control notification handler code here 4 if (m_pcomm.get_PortOpen()) 5 { 6 m_pcomm.put_PortOpen(false); 7 } 8 if (m_pcomm.get_PortOpen()) 9 { 10 AfxMessageBox(_T("Can not close serial port.")); 11 } 12 else 13 { 14 GetDlgItem(IDC_BUTTON2)->ShowWindow(SW_HIDE); 15 GetDlgItem(IDC_BUTTON1)->ShowWindow(SW_SHOW); 16 } 17 }
- 串口控件事件处理,用于处理串口事件
1 void CSerialComDlg::OnCommMscomm1() 2 { 3 VARIANT variant_inp; 4 COleSafeArray safearray_inp; 5 LONG len; 6 unsigned char rxdata[100]; 7 long i; 8 CString str(rxdata); 9 CString send = "C565A3D832045170CF2712239BADA944B39EB55E05063FA64F93CCB0440FA32E780B3CA947B3C8D0AB36DF1B4B"; 10 // TODO: Add your message handler code here 11 if (m_pcomm.get_CommEvent()==2) 12 { 13 variant_inp = m_pcomm.get_Input(); //get byte from input buffer 14 safearray_inp = variant_inp; //VARIANTD to COleSafeArray type 15 len = safearray_inp.GetOneDimSize(); //length of rx data 16 for (i = 0; i < len; i++) 17 { 18 safearray_inp.GetElement(&i, rxdata + i); 19 } 20 m_Edit1 = ""; 21 for ( i = 0; i < len; i++) 22 { 23 str.Format(_T("%X"), rxdata[i]); 24 if (strlen(str) == 0) 25 m_Edit1 += "00"; 26 else if (strlen(str) == 1) 27 { 28 m_Edit1 += "0"; 29 m_Edit1 += str; 30 } 31 else 32 m_Edit1 += str; 33 } 34 m_pcomm.put_Output(COleVariant(send)); 35 UpdateData(false); 36 } 37 }
- 因为我们将两个按键叠加一起,当按下open按键,且串口打开正常时,显示close按键,当按下close按键,且串口关闭正常时,显示open按键。所以我们在启动对话框的时候,需要先将close按键隐藏,而open按键显示。因此我们需在对话框初始化时,添加代码:
// Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here GetDlgItem(IDC_BUTTON2)->ShowWindow(SW_HIDE); return TRUE; // return TRUE unless you set the focus to a control
- 至此,我们的项目就完成了,但是,我们编译的时候,可能会提示错误提示,因为我们调用了strlen函数,所以我们需要将项目设置一下
Use Multi-Byte Character Set
点击运行,项目完成。
记录编程路上的点点滴滴,你会发现代码给我们的乐趣是那么的令人回味。
谢谢.