文章目录
- Qt QSerialPort数据发送和接收DataComm
- 2.添加 Qt Serial Port 模块
- 3.实例源码
Qt QSerialPort数据发送和接收DataComm
Qt 框架的Qt Serial Port 模块提供了访问串口的基本功能,包括串口通信参数配置和数据读写,使用 Qt Serial Port 模块就可以很方便地编写具有串口通信功能的应用程序。
- 创建一个基于
QMainWindow
应用程序
2.添加 Qt Serial Port 模块
Qt Serial Port 模块用于串口通信编程,要在一个项目中使用 Qt Serial Port 模块,需要在项目配置文件中加入一行语句:QT += serialport
Qt Serial Port 模块中只包含有两个类:QSerialPortInfo
和 QSerialPort
。
3.实例源码
头文件datacomm.h
#ifndef DATACOMM_H
#define DATACOMM_H#include <QMainWindow>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QTimer>QT_BEGIN_NAMESPACE
namespace Ui {
class DataComm;
}
QT_END_NAMESPACEclass DataComm : public QMainWindow
{Q_OBJECTpublic:DataComm(QWidget *parent = nullptr);~DataComm();
private slots:void clear_recv();void clear_send();void on_com_recv();void on_com_send();void on_com_open();void on_com_changed(int index);void on_timeout();void on_check_state_changed(int);void get_interval();
private:void send();Ui::DataComm *ui;QSerialPort comPort;bool bCircle;int interval;QTimer *timer;QByteArray stdCmd;QString strCmd;
};
#endif // DATACOMM_H
源文件datacomm.cpp
#include "datacomm.h"
#include "ui_datacomm.h"
#include <QMessageBox>DataComm::DataComm(QWidget *parent): QMainWindow(parent), ui(new Ui::DataComm)
{ui->setupUi(this);foreach (QSerialPortInfo portInfo, QSerialPortInfo::availablePorts()) {ui->comboBoxPort->addItem(portInfo.portName());}ui->comboBoxPort->setCurrentIndex(2);connect(ui->comboBoxPort,SIGNAL(currentIndexChanged(int)),this,SLOT(on_com_changed(int)));ui->pushButtonOpen->setEnabled(ui->comboBoxPort->count()>0);ui->pushButtonSend->setEnabled(false);connect(ui->pushButtonOpen,SIGNAL(clicked()),this,SLOT(on_com_open()));connect(ui->pushButtonSend,SIGNAL(clicked()),this,SLOT(on_com_send()));ui->comboBoxBaud->clear();foreach (qint32 baud, QSerialPortInfo::standardBaudRates()) {ui->comboBoxBaud->addItem(QString::number(baud));}ui->comboBoxBaud->setCurrentText("9600");ui->comboBoxCheck->addItem("NONE");ui->comboBoxCheck->addItem("ODD");ui->comboBoxCheck->addItem("EVEN");ui->comboBoxCheck->addItem("SPACE");ui->comboBoxCheck->addItem("MARK");ui->comboBoxFlowCtrl->addItem("NONE");ui->comboBoxFlowCtrl->addItem("HARD");ui->comboBoxFlowCtrl->addItem("SOFT");ui->comboBoxDataBit->addItem("5");ui->comboBoxDataBit->addItem("6");ui->comboBoxDataBit->addItem("7");ui->comboBoxDataBit->addItem("8");ui->comboBoxDataBit->setCurrentText("8");ui->comboBoxStopBit->addItem("1");ui->comboBoxStopBit->addItem("1.5");ui->comboBoxStopBit->addItem("2");timer = new QTimer(this);ui->lineEditTime->setText("1000");interval = 1000;connect(ui->pushButtonClearRecv,&QPushButton::clicked,this,&DataComm::clear_recv);connect(ui->pushButtonClearSend,&QPushButton::clicked,this,&DataComm::clear_send);connect(timer,&QTimer::timeout,this,&DataComm::on_timeout);connect(ui->lineEditTime,&QLineEdit::textChanged,this,&DataComm::get_interval);connect(&comPort,&QIODevice::readyRead,this,&DataComm::on_com_recv);connect(ui->checkBoxCircle,&QCheckBox::stateChanged,this,&DataComm::on_check_state_changed);resize(800,600);
}DataComm::~DataComm()
{delete ui;
}void DataComm::clear_recv()
{ui->plainTextEditRecv->clear();
}void DataComm::clear_send()
{ui->plainTextEditSend->clear();
}
void DataComm::on_com_open()
{if(comPort.isOpen()) {comPort.close();ui->comboBoxPort->setEnabled(true);ui->comboBoxBaud->setEnabled(true);ui->comboBoxCheck->setEnabled(true);ui->comboBoxDataBit->setEnabled(true);ui->comboBoxStopBit->setEnabled(true);ui->comboBoxFlowCtrl->setEnabled(true);ui->pushButtonSend->setEnabled(false);ui->pushButtonOpen->setText("打开");}else {int index = ui->comboBoxPort->currentIndex();QList<QSerialPortInfo> comList = QSerialPortInfo::availablePorts();QSerialPortInfo portInfo = comList.at(index);comPort.setPort(portInfo);comPort.setReadBufferSize(2048);comPort.setBaudRate(ui->comboBoxBaud->currentText().toInt());int value = ui->comboBoxDataBit->currentText().toInt();comPort.setDataBits(QSerialPort::DataBits(value));value = ui->comboBoxCheck->currentText().toInt();if(value != 0) {value ++;}comPort.setParity(QSerialPort::Parity(value));value = ui->comboBoxStopBit->currentText().toInt();comPort.setStopBits(QSerialPort::StopBits(value));value = ui->comboBoxFlowCtrl->currentText().toInt();comPort.setFlowControl(QSerialPort::FlowControl(value));if(comPort.open(QIODevice::ReadWrite)) {ui->comboBoxPort->setEnabled(false);ui->comboBoxBaud->setEnabled(false);ui->comboBoxCheck->setEnabled(false);ui->comboBoxDataBit->setEnabled(false);ui->comboBoxStopBit->setEnabled(false);ui->comboBoxFlowCtrl->setEnabled(false);ui->pushButtonSend->setEnabled(true);ui->pushButtonOpen->setText("关闭");}}
}void DataComm::get_interval()
{int val = ui->lineEditTime->text().toInt();if(val > 0) {interval = val;}else {ui->lineEditTime->setText(QString::number(interval));}
}void DataComm::on_check_state_changed(int)
{bCircle = ui->checkBoxCircle->isChecked();if(!bCircle) {if(timer->isActive()) {timer->stop();ui->pushButtonSend->setEnabled(true);}}
}
void DataComm::send()
{ui->plainTextEditRecv->appendPlainText("Tx: "+ strCmd );comPort.write((const QByteArray )stdCmd);
}void DataComm::on_com_send()
{strCmd = ui->plainTextEditSend->toPlainText();if(strCmd.isEmpty()) {QMessageBox::information(this,tr("发送内容为空"),tr("发送内容为空!"));return;}QByteArray ba = QByteArray (strCmd.toUtf8());stdCmd = ba;send();bCircle = ui->checkBoxCircle->isChecked();if(bCircle) {ui->pushButtonSend->setEnabled(false);timer->start(interval);}
}void DataComm::on_timeout()
{send();
}void DataComm::on_com_recv()
{if(comPort.bytesAvailable()) {comPort.waitForReadyRead(100);QByteArray all = comPort.read(1024);QString str(all);if(!str.isEmpty()){ui->plainTextEditRecv->appendPlainText("Rx: "+ str );}}
}void DataComm::on_com_changed(int index)
{}
源文件main.cpp
#include "datacomm.h"#include <QApplication>
#include <QLocale>
#include <QTranslator>int main(int argc, char *argv[])
{QApplication a(argc, argv);QTranslator translator;const QStringList uiLanguages = QLocale::system().uiLanguages();for (const QString &locale : uiLanguages) {const QString baseName = "DataCom_" + QLocale(locale).name();if (translator.load(":/i18n/" + baseName)) {a.installTranslator(&translator);break;}}DataComm w;w.show();return a.exec();
}
nguages) {
const QString baseName = “DataCom_” + QLocale(locale).name();
if (translator.load(“:/i18n/” + baseName)) {
a.installTranslator(&translator);
break;
}
}
DataComm w;
w.show();
return a.exec();
}