Qt使用串口

头文件:

#include 
#include 

先创建一个串口类:

QSerialPort *m_serialPort = new QSerialPort();

构析函数:

    if (m_serialPort->isOpen())
    {
        m_serialPort->close();
    }
    delete m_serialPort;

搜索能用的串口,放入comboBox:

    ui->comboBox->clear();
    for (QSerialPortInfo info : QSerialPortInfo::availablePorts()) {
  #ifdef Q_OS_WIN
        ui->comboBox->addItem(info.portName());
  #else
        ui->serial_port_combo_box->addItem(info.systemLocation());
  #endif
    }

选择串口,按下确定按钮:

void MainWindow::on_pushButton_summit_clicked()
{
    if(m_serialPort->isOpen())//如果串口已经打开了 先给他关闭了
    {
        m_serialPort->clear();
        m_serialPort->close();
    }
    QString devName = ui->comboBox->currentText();
    if(devName == ""){
        //qDebug()<<"nothing";
        QMessageBox::critical(NULL, "错误!!", "尚未选择串口或串口无效", QMessageBox::Ok);
    }
    else{
        m_serialPort->setPortName(devName);
        if(!m_serialPort->open(QIODevice::ReadWrite))//用ReadWrite 的模式尝试打开串口
        {
            QMessageBox::critical(NULL, "错误!!", "串口打开失败", QMessageBox::Ok);
            return;
        }
    }
}

 

你可能感兴趣的:(QT)