(文章目录)
前言
本篇文章将正式的带大家实现串口的查找添加,和打开串口的功能。
一、查找存在的串口将串口添加进选择框
创建一个QList用于存储串口的信息。
QList<QSerialPortInfo> m_portList;
在帮助文档中我们看到: 使用availablePorts()这个函数可以返回当前存在的串口链表。 得到这个链表后,我们使用for循环遍历这个链表将每一个链表的名字添加进入我们创建好存放串口名字的QComBox中。
/*查找电脑当前可用串口*/
void SerialPort::FindAndAddSerialPort()
{
/*返回当前存在的串口链表*/
m_portList = QSerialPortInfo::availablePorts();
// 遍历每个可用的串口
for (int i = 0; i < m_portList.count(); i++)
{
ui->Serialcb->addItem(QString(m_portList[i].portName()));
}
}
编写好这个函数后在构造函数中调用,因为我们需要让我们的串口助手运行后就马上检测我们PC机上的串口情况然后加他添加进入QComBox中显示出来。
/*查找所有可用串口*/
FindAndAddSerialPort();
二、打开串口功能的实现
在ui文件中点击跳转到槽,这样就可以直接进入打开串口按键的槽函数了。 在打开串口之前我们需要先从QComBox中获取当前串口的配置信息: 这里需要注意的就是串口配置参数类型和QString类型之间的转换,大家看下面代码就能看明白了,这里就不多说。
/*获取串口配置参数*/
void SerialPort::GetSerialPortPara()
{
m_COM = ui->Serialcb->currentText();
m_Baud = QSerialPort::BaudRate(ui->Baudcb->currentText().toInt());
m_databits = QSerialPort::DataBits(ui->datacb->currentText().toInt());
if(ui->paritycb->currentText() == "None")
{
m_parity = QSerialPort::NoParity;
}
else if(ui->paritycb->currentText() == "Odd")
{
m_parity = QSerialPort::OddParity;
}
else if(ui->paritycb->currentText() == "Even")
{
m_parity = QSerialPort::EvenParity;
}
else if(ui->paritycb->currentText() == "Mark")
{
m_parity = QSerialPort::MarkParity;
}
else if(ui->paritycb->currentText() == "Space")
{
m_parity = QSerialPort::SpaceParity;
}
if(ui->stopcb->currentText() == "One")
{
m_stopbits = QSerialPort::OneStop;
}
else if(ui->stopcb->currentText() == "OnePointFive")
{
}
else if(ui->stopcb->currentText() == "Two")
{
m_stopbits = QSerialPort::TwoStop;
}
}
获取到参数信息后我们打开串口:
/*设置要打开的串口和配置对应的参数*/
bool SerialPort::OpenSerialPort(QString COM, QSerialPort::BaudRate BaudRate, QSerialPort::DataBits DataBits, QSerialPort::Parity Parity, QSerialPort::StopBits StopBits)
{
bool ret = false;
// 配置串口参数
m_SerialPort.setPortName(COM); //设置串口号
m_SerialPort.setBaudRate(BaudRate); //设置波特率
m_SerialPort.setDataBits(DataBits); //设置数据位
m_SerialPort.setParity(Parity); //设置校验位
m_SerialPort.setStopBits(StopBits); //设置停止位
// 打开串口
if (m_SerialPort.open(QIODevice::ReadWrite))
{
qDebug() << "串口打开成功";
ret = true;
}
else
{
qDebug() << "串口打开失败";
ui->Statelab->setText("Open failed!");
QMessageBox::warning(this, "警告", "打开串口出错,串口被占用或已拔出!");
ret = false;
}
return ret;
}
这些都编写完成后编写打开按键槽函数: 这里主要需要注意的就是打开串口后,串口的配置是不能进行修改的所以需要把对应的控件设置为不可编辑的状态,同样的关闭串口后也需要进行对应的设置。
/*打开串口按键*/
void SerialPort::on_openbtn_clicked()
{
m_open_close = !m_open_close;
if(m_open_close)
{
/*获取串口配置参数*/
GetSerialPortPara();
/*打开串口*/
bool ret = OpenSerialPort(m_COM, m_Baud, m_databits, m_parity, m_stopbits);
if(ret)
{
ui->Statelab->setText(ui->Serialcb->currentText()+ " " + "Opend");
ui->openbtn->setText("关闭串口");
}
else
{
m_open_close = !m_open_close;
}
}
else
{
m_SerialPort.close();
ui->openbtn->setText("打开串口");
ui->Statelab->setText(ui->Serialcb->currentText()+ " " + "Closed");
}
SetSerialPortPara(!m_open_close);
}
总结
本篇文章我们完成了串口的打开和查找,下一篇文章我们将完成串口的接收和发送。