16,550
社区成员
发帖
与我相关
我的任务
分享
void CSCommTestDlg::OnButtonClickedOpenSerial()
{
CString str;
GetDlgItem(OpenButton)->GetWindowText(str);
if(str=="打开串口")
{
if(m_ctrlComm.GetPortOpen())
m_ctrlComm.SetPortOpen(FALSE);
m_ctrlComm.SetCommPort(1); //选择com1
if( !m_ctrlComm.GetPortOpen())
{
m_ctrlComm.SetPortOpen(TRUE);//打开串口
SetDlgItemText(OpenButton,"串口关闭");
m_ctrlComm.SetSettings("9600,n,8,1"); //波特率9600,无校验,8个数据位,1个停止位
m_ctrlComm.SetInputMode(1); //以二进制方式检到数据
m_ctrlComm.SetRThreshold(1);
//参数1表示每当串口接收缓冲区中有多于或等于1个字符时将引发一个接收数据的OnComm事件
m_ctrlComm.SetInputLen(0); //设置当前接收区数据长度为0
m_ctrlComm.GetInput();//先预读缓冲区以清除残留数据
AfxMessageBox("成功打开串口");
}
else
AfxMessageBox("cannot open serial port");
}
else
{
m_ctrlComm.SetPortOpen(FALSE);//关闭串口
SetDlgItemText(OpenButton,"串口打开");
AfxMessageBox("成功关闭串口");
}
}