111205
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QModbusRtuSerialMaster>
#include <QSerialPort>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_pushButton_clicked();
void replyFinished();
void on_pushButton_2_clicked();
private:
Ui::MainWindow *ui;
QModbusRtuSerialMaster *rtuMaster;
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
rtuMaster=new QModbusRtuSerialMaster(this);
rtuMaster->setConnectionParameter(QModbusDevice::SerialPortNameParameter,"COM3");
rtuMaster->setConnectionParameter(QModbusDevice::SerialBaudRateParameter,9600);
rtuMaster->setConnectionParameter(QModbusDevice::SerialParityParameter,QSerialPort::EvenParity);
rtuMaster->setConnectionParameter(QModbusDevice::SerialDataBitsParameter,QSerialPort::Data8);
rtuMaster->setConnectionParameter(QModbusDevice::SerialStopBitsParameter,QSerialPort::OneStop);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
QModbusDataUnit unit(QModbusDataUnit::HoldingRegisters,ui->lineEdit_2->text().toInt(),2);
QModbusReply *reply=rtuMaster->sendReadRequest(unit,1);
if(reply&&!reply->isFinished())
{
connect(reply,QModbusReply::finished,this,MainWindow::replyFinished);
}
}
void MainWindow::on_pushButton_2_clicked()
{
if(rtuMaster->state()!=QModbusRtuSerialMaster::ConnectedState)
{
rtuMaster->connectDevice();
}
QVector<quint16> data;
data<<5<<24;
QModbusDataUnit uint(QModbusDataUnit::HoldingRegisters,ui->lineEdit_2->text().toInt(),data);
rtuMaster->sendWriteRequest(uint,1);
}
void MainWindow::replyFinished()
{
QModbusReply *reply=qobject_cast<QModbusReply *>(sender());
if(reply)
{
QModbusDataUnit uint=reply->result();
reply->deleteLater();
ui->lineEdit->setText(QString::number(uint.value(0)));
}
}
标签:void,QModbusDevice,Modbus,ui,完成,串口,reply,rtuMaster,MainWindow From: https://www.cnblogs.com/dq0618/p/17830572.html