本文在QT5.14平台,基于QModbusClientTcp类,实现了客户端对单个寄存器的读写,用ModbusSlave做服务器做测试。
1.界面
(1)更改读按钮的名称为bt_Read
(2)更改写按钮的名称为bt_Write
2.修改pro文件的第三行
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets serialbus
3.修改mainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QModbusTcpClient>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_bt_Read_clicked();
void on_bt_Write_clicked();
void ReplyData();
private:
Ui::MainWindow *ui;
QModbusTcpClient *client;
};
#endif // MAINWINDOW_H
4.修改mainWindow.c
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->setWindowTitle("ModbusTCPClient");
client=new QModbusTcpClient(this);
client->setConnectionParameter(QModbusDevice::NetworkAddressParameter,"127.0.0.1");
client->setConnectionParameter(QModbusDevice::NetworkPortParameter,502);
client->connectDevice();
}
MainWindow::~MainWindow()
{
if(client->state()==QModbusTcpClient::ConnectedState)
{
client->disconnectDevice();
}
delete ui;
}
void MainWindow::on_bt_Read_clicked()
{
QModbusDataUnit unit(QModbusDataUnit::HoldingRegisters,500,1);
unit.setValue(0,ui->textEdit->toPlainText().toInt());
QModbusReply *reply=client->sendReadRequest(unit,1);
if(reply)
{
if(!reply->isFinished())
{
connect(reply,&QModbusReply::finished,this,&MainWindow::ReplyData);
return;
}
}
reply->deleteLater();
}
void MainWindow::on_bt_Write_clicked()
{
QModbusDataUnit unit(QModbusDataUnit::HoldingRegisters,500,1);
unit.setValue(0,ui->textEdit->toPlainText().toInt());
QModbusReply *reply=client->sendWriteRequest(unit,1);
if(reply)
{
reply->deleteLater();
}
}
void MainWindow::ReplyData()
{
QModbusReply *reply=(QModbusReply *)(sender());
QModbusDataUnit unit=reply->result();
reply->deleteLater();
if(unit.valueCount()>0)
{
ui->textEdit->setText(QString::number(unit.value(0)));
}
}