新浪博客

串口初始化程序代码

2013-10-12 22:55阅读:
串口初始化程序代码
—红色部分是需要添加的,其余不一定对,每条指令完成的功能在指令后面都有说明。
BOOL CSCommTestDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add 'About...' menu item to system menu.

// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);

CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// 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
m_ctrlComm.SetCommPort(1);
//选择com1
m_ctrlComm.SetInputMode(1);
//设置接收数据拣出模式1,及二进制模式
m_ctrlComm.SetInBufferSize(1024);
//设置串口接收缓存区大小为1024字节
m_ctrlComm.SetOutBufferSize(512);
//设置串口发送缓存区大小为512字节
m_ctrlComm.SetSettings('9600,n,8,1');
//波特率9600,无校验,8个数据位,1个停止位
m_ctrlComm.SetPortOpen(TRUE);
//打开串口
m_ctrlComm.SetRThreshold(1);
//参数1表示每当串口接收缓冲区中有多于或等于1个字符时将引发一个接收数据的OnComm事件
m_ctrlComm.SetInputLen(0);
//设置当前接收区数据长度为0
m_ctrlComm.SetInBufferCount(0);
//清空接收缓存区,即清除接收缓存区中残留的数据

return TRUE; // return TRUE unless you set the focus to a control
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
串口事件消息响应处理函数的程序代码,
即串口接收数据处理程序
void CMSCommTestDlg::OnComm()
{
// TODO: Add your control notification handler code here
VARIANT variant_inp;
COleSafeArray safearray_inp;
LONG len,k;
BYTE rxdata[2048]; //设置BYTE型数组
CString strtemp;
if(m_ctrlComm.GetCommEvent()==2) //事件值为2表示接收数据事件
{
variant_inp=m_ctrlComm.GetInput(); //读接收数据缓存
safearray_inp=variant_inp; //VARIANT型转换为ColeSafeArray
len=safearray_inp.GetOneDimSize(); //得到有效数据长度
for(k=0;k<len;k++)
safearray_inp.GetElement(&k,rxdata+k); //转换为BYTE型数组
for(k=0;k<len;k++) //将数组转换为Cstring型变量
{
BYTE bt = *(char *)(rxdata+k); //字符型
strtemp.Format('%c',bt); //将字符送入临时变量strtemp
m_strEditRXData+=strtemp; //加入接收编辑框对应字符串型映射变量中
}
}
UpdateData(FALSE); //更新编辑框内容,即在接收显示框中显示接收数据
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
串口发送程序代码
void CMSCommTestDlg::OnButtonManualsend()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
m_ctrlComm.SetOutput(COleVariant(m_strEditTXData));
}


串口初始化程序代码

我的更多文章

下载客户端阅读体验更佳

APP专享