《使用Qt实现串口通信的精彩之旅》

使用Qt5.1以上版本

首先新建Qt Gui工程TestSerialPort。设计程序界面

对于指示灯,他是一个label标签,设置宽度24*24。右键点击它,改变样式表

编辑样式表

在工程文件TestSerialPort.pro中加入

QT		  += serialport

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

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

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

public:
    ...
    bool serialport_init();

窗口类中,加入槽函数

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

窗口类中,定义串口指针

private:
    ...
    QSerialPort* m_serialport;

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

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()));

实现初始化串口函数

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;
}

实现打开串口函数

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("关闭串口");
    }

}

实现接收数据函数

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

实现发送数据函数

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

我使用虚拟串口软件模拟了两个串口,并且互相连通,也就是从com2发送的数据,com3可用接收,反过来也一样。
软件使用com2,串口调试工具使用com3,就可以测试软件的运行情况

效果:

物联沃分享整理
物联沃-IOTWORD物联网 » 《使用Qt实现串口通信的精彩之旅》

发表评论