标签:
MFC下串口编程使用最多的两种方法是读取注册表和使用mscomm组件,都有着或多或少的缺陷,调用系统SDK比较麻烦,而MSCOMm组件最多支持16个串口,串口号大于16的时候无法打开,遇到这种情况,可以使用一个名为pcommlite的串口通讯库,下载安装之后,解压出来的文件包括
根据编译的平台选择相应的lib文件加入工程,并加入pcomm.h文件
2.打开串口,各种库宏定义
switch(comBaud)
{
case 0:
m_comBaud = B1200;
break;
case 1:
m_comBaud = B2400;
break;
case 2:
m_comBaud = B4800;
break;
case 3:
m_comBaud = B9600;
break;
case 4:
m_comBaud = B19200;
break;
case 5:
m_comBaud = B38400;
break;
case 6:
m_comBaud = B57600;
break;
case 7:
m_comBaud = B115200;
break;
case 8:
m_comBaud = B230400;
break;
}
switch(comStopBit)
{
case 0:
m_comStopBit = STOP_1;
break;
case 1:
m_comStopBit = STOP_2;
break;
}
switch (comDataLength)
{
case 0:
m_comDataLength = BIT_5;
break;
case 1:
m_comDataLength = BIT_6;
break;
case 2:
m_comDataLength = BIT_7;
break;
case 3:
m_comDataLength = BIT_8;
break;
}
switch(comCheckSum)
{
case 0:
m_comChecksum = P_NONE;
break;
case 1:
m_comChecksum = P_ODD;
break;
case 2:
m_comChecksum = P_EVEN;
break;
}
config = m_comDataLength|m_comStopBit|m_comChecksum;
//开始串口配置
if( sio_open(m_comPort) != SIO_OK)
{
MessageBox("串口打开失败","提示",MB_OK);
this->serialsIsOpen = false;
m_comPort = 0;
return;
}
sio_flowctrl(m_comPort,0x00);//关闭硬件流控制
sio_lctrl(m_comPort,0x00);//关闭RTS DTR
sio_ioctl(m_comPort,m_comBaud,config);
sio_flush(m_comPort,2);
this->GetDlgItem(IDC_BUTTON_SERIAL_CONTROL)->SetWindowText("关闭串口");
GetDlgItem(IDC_COMBO_Serial_Num_Select)->EnableWindow(FALSE);
GetDlgItem(IDC_COMBO_Serial_Baud_Select)->EnableWindow(FALSE);
GetDlgItem(IDC_COMBO_Serial_Data_Select)->EnableWindow(FALSE);
GetDlgItem(IDC_COMBO_Serial_Parity_Select)->EnableWindow(FALSE);
GetDlgItem(IDC_COMBO_Serial_Stop_Select)->EnableWindow(FALSE);
this->serialsIsOpen = true;
}
3.串口发送数据 sio_lstatus() sio_write()
//检查串口是否打开,打开就发送
if(serialsIsOpen == true)
{
//变量打开了,要去测试串口状态
if(sio_lstatus(m_comPort)>= 0)
{
CString str1;
sendString.Empty();
//没有对\r\n特殊处理
((CEdit*)GetDlgItem(IDC_EDIT3))->GetWindowText(str1);
sendString.AppendFormat("%s",str1);
sio_write(m_comPort,sendString.GetBuffer(),sendString.GetLength());
}
else
{
//说明串口已经丢失
MessageBox("串口丢失,请关闭后重新打开","错误",MB_OK);
}
}
else
{
//说明串口已经丢失
MessageBox("请先打开串口","错误",MB_OK);
}
4.设定定时器,用于串口接收数据
5.在定时器中接收数据 sio_read()
void CLPC1768_PAD_OTG_DebugDlg::SerialsProcessBuffer( void )
{
serialReadTemp.Empty();
if(m_comPort > 0 && this->serialsIsOpen == true)
{
char readBuffer[1024] = {0};
// sio_flush(m_comPort,1);
int length = sio_read(m_comPort,readBuffer,1024);
if(length > 0)
{
for(int i = 0; i < length; i++)
{
serialReadTemp.AppendChar(readBuffer[i]);
}
}
}
}
该库还有很多借口用于控制DTR RTS等,使用方便,详情查看帮助文档
标签:
原文地址:http://www.cnblogs.com/dengxiaojun/p/4279504.html