qt通信:串口通信

  好久没有使用串口通信,所以有些数据老是忘记,所以找了个时间总结一下,下次可以直接复制,不用再写了。  

  

  1.在工程文件.pro文件中加入

   

 QT += serialport

  2.之后点击构建,执行一次qmake
   在窗口类的头文件中,加入串口通信用到的头文件

#include <QtSerialPort/QSerialPort>         // 提供访问串口的功能
#include <QtSerialPort/QSerialPortInfo>      // 提供系统中存在的串口信息

  3.窗口类中,加入初始化串口函数声明

public:
    ...
    bool serialport_init();

  4.槽函数

private slots:
    void send_data();//发送串口数据
    void receive_data();//接收串口数据
    void open_serialport();//串口开启/关闭控制

  5.定义指针

private:
    ...
    QSerialPort* m_serialport;

  6.在窗口类的构造函数中,创建串口。初始化串口,关联发送数据按钮、串口接受数据和打开串口按钮对应的功能函数

m_serialport = new QSerialPort();
serialport_init();
connect(m_serialport,SIGNAL(readyRead()),this,SLOT(receive_data()));
connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(send_data()));
connect(ui->pushButton_2,SIGNAL(clicked()),this,SLOT(open_serialport()));

  7.实现初始化串口函数

bool MainWindow::serialport_init(){
	//获得所有可用端口列表
    QList<QSerialPortInfo> serialPortInfoList = QSerialPortInfo::availablePorts();
    if(serialPortInfoList.isEmpty()){
        return false;
    }
    QList<QSerialPortInfo>::iterator iter = serialPortInfoList.begin();
    //将所有端口添加到界面的下拉列表中
    while(iter!=serialPortInfoList.end()){
        ui->comboBox->addItem(iter->portName());
        iter++;
    }
    return true;
}

  8.实现打开串口函数

void MainWindow::open_serialport(){
	//判断串口开启状态
    if(m_serialport->isOpen()){
        //若串口已经打开,则关闭它,设置指示灯为红色,设置按钮显示“打开串口”
        m_serialport->clear();
        m_serialport->close();
        ui->label->setStyleSheet("background-color:rgb(255,0,0);border-radius:12px;");
        ui->pushButton_2->setText("打开串口");
        return;
    }else{
   		 //若串口没有打开,则打开选择的串口,设置指示灯为绿色,设置按钮显示“关闭串口”
        m_serialport->setPortName(ui->comboBox->currentText());
        m_serialport->open(QIODevice::ReadWrite);
        m_serialport->setBaudRate(QSerialPort::Baud115200);
        m_serialport->setDataBits(QSerialPort::Data8);
        m_serialport->setParity(QSerialPort::NoParity);
        m_serialport->setStopBits(QSerialPort::OneStop);
        m_serialport->setFlowControl(QSerialPort::NoFlowControl);
        ui->label->setStyleSheet("background-color:rgb(0,255,0);border-radius:12px;");
        ui->pushButton_2->setText("关闭串口");
    }

}

  9.实现接收数据函数

void MainWindow::receive_data(){
    QByteArray message;
    message.append(m_serialport->readAll());
    //使textEdit控件追加显示接收到的数据
    ui->textEdit->append(message);
}

  10.实现发送数据

  

void MainWindow::send_data(){
    QString message = ui->lineEdit->text();
    QByteArray messageSend;
    messageSend.append(message);
    m_serialport->write(messageSend);
}

  

posted @ 2025-01-15 11:12  小范同学的博客  阅读(213)  评论(0)    收藏  举报