QT学习笔记——串口通信

一、test.pro

添加模块:

    QT +=  serialport

二、mainwindow.h

添加头文件:

    #include 
    #include 

修改类:

    private:
        QSerialPort *serial;
    private slots:
        void ReadData();
        void SendData();
        void on_pushButton_findcom_clicked();
        void on_pushButton_opencom_clicked()

三、mainwindow.cpp

1.查找串口

按钮 pushButton_findcom,下拉菜单 comboBox_com1

    void MainWindow::on_pushButton_findcom_clicked(){
            foreach (const QSerialPortInfo &info,QSerialPortInfo::availablePorts()){
                QSerialPort serial;
                serial.setPort(info);
                if(serial.open(QIODevice::ReadWrite)){
                    ui->comboBox_com1->addItem(serial.portName());
                    serial.close();
                }
            }
            ui->comboBox_com1->setCurrentIndex(0); //设置波特率下拉菜单默认显示第0项
    }

2.打开串口

按钮 pushButton_opencom,text:打开串口

    void MainWindow::on_pushButton_opencom_clicked(){
        if(ui->pushButton_opencom->text() == tr("打开串口")){
            serial = new QSerialPort;
            serial->setPortName(ui->comboBox_com1->currentText());
            serial->open(QIODevice::ReadWrite);
            serial->setBaudRate(QSerialPort::Baud115200);
            serial->setDataBits(QSerialPort::Data8);
            serial->setParity(QSerialPort::NoParity);
            serial->setStopBits(QSerialPort::OneStop);
            serial->setFlowControl(QSerialPort::NoFlowControl);
            ui->pushButton_opencom->setText(tr("关闭串口"));
            QObject::connect(serial,SIGNAL(readyRead()),this,SLOT(ReadData()));
        }
        else{
            //关闭串口
            serial->clear();
            serial->close();
            serial->deleteLater();
            ui->pushButton_opencom->setText(tr("打开串口"));
        }
    }

3.读取数据

void MainWindow::ReadData(){
    QByteArray byte = serial->readAll();
    //校验帧头
    if(byte.size()<11)return;
    if(!((byte.toHex().at(0)=='5'&&byte.toHex().at(1)=='a')||(byte.toHex().at(0)=='5'&&byte.toHex().at(1)=='A')))return;
   /* QString showstr;
    for(int i=0;i

4.发送数据

void MainWindow::SendData(){
        QByteArray ba;
        ba.resize(4);
        ba[0]=0x5a;
        ba[1]=0x00;
        ba[2]=0x00;
        ba[3]=ba[0]+ba[1]+ba[2];
        serial->write(ba);
    }
}

你可能感兴趣的:(QT学习笔记——串口通信)