widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QModbusTcpClient>
#include<iostream>
using namespace std;
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void on_btnRead_clicked();
void on_btnWrite_clicked();
void replyData();
private:
Ui::Widget *ui;
QModbusTcpClient *client;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
client = new QModbusTcpClient(this);
client->setConnectionParameter(QModbusDevice::NetworkAddressParameter,"192.168.5.20");
client->setConnectionParameter(QModbusDevice::NetworkPortParameter,502);
client->connectDevice();
}
Widget::~Widget()
{
if (client->state()==QModbusTcpClient::ConnectedState){
client->disconnectDevice();
}
delete ui;
}
void Widget::on_btnRead_clicked()
{
QModbusDataUnit unit(QModbusDataUnit::HoldingRegisters,0,1);
QModbusReply* reply = client->sendReadRequest(unit,1);
if (reply){
if (!reply->isFinished()){
//connect里面的参数必须全部是指针,B站视频里在这里有错误,可能是QT版本的问题
connect(reply,&QModbusReply::finished,this,&Widget::replyData);
return;
}
}
}
void Widget::on_btnWrite_clicked()
{
QModbusDataUnit unit(QModbusDataUnit::HoldingRegisters,0,1);
unit.setValue(0,ui->lineEdit->text().toUInt());
QModbusReply *reply = client->sendWriteRequest(unit,1);
if (reply){
reply->deleteLater();
}
}
void Widget::replyData(){
// cout<<123<<endl;
QModbusReply* reply = (QModbusReply*)(sender());
QModbusDataUnit unit = reply->result();
reply->deleteLater();
if (unit.valueCount()>0){
ui->lineEdit->setText(QString::number(unit.value(0)));
}
}
widget.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Widget</class>
<widget class="QWidget" name="Widget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>364</height>
</rect>
</property>
<property name="windowTitle">
<string>Widget</string>
</property>
<widget class="QWidget" name="horizontalLayoutWidget">
<property name="geometry">
<rect>
<x>50</x>
<y>60</y>
<width>441</width>
<height>80</height>
</rect>
</property>
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="spacing">
<number>33</number>
</property>
<item>
<widget class="QLineEdit" name="lineEdit"/>
</item>
<item>
<widget class="QPushButton" name="btnRead">
<property name="text">
<string>read</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnWrite">
<property name="text">
<string>write</string>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
<resources/>
<connections/>
</ui>
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
python代码实现
import sys
from PySide6.QtWidgets import *
from PySide6.QtCore import *
from PySide6.QtSerialBus import QModbusTcpClient,QModbusReply,QModbusDataUnit,QModbusDevice
class Window(QWidget):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.btn = QPushButton("read",self)
self.btn2 = QPushButton("write",self)
self.btn.move(50,50)
self.btn2.move(150,50)
self.btn.clicked.connect(self.on_btnRead)
self.btn2.clicked.connect(self.on_btnWrite)
self.client = QModbusTcpClient(self)
self.client.setConnectionParameter(QModbusDevice.ConnectionParameter.NetworkAddressParameter,"192.168.5.20")
self.client.setConnectionParameter(QModbusDevice.ConnectionParameter.NetworkPortParameter,502)
if self.client.connectDevice():
QMessageBox.information(self, "tips", "sucess")
else:
QMessageBox.information(self, "tips", "wrong")
def on_btnRead(self):
readunit:QModbusDataUnit = QModbusDataUnit(QModbusDataUnit.RegisterType.HoldingRegisters,0,10)
reply:QModbusReply = self.client.sendReadRequest(readunit,1)
if reply:
while not reply.isFinished():
QCoreApplication.processEvents()
if reply.error() == QModbusDevice.Error.NoError:
relustunit: QModbusDataUnit = reply.result()
result: str = ""
for i in range(relustunit.valueCount()):
result += str(relustunit.value(i)) + " "
print(result)
else:
print(self.client.errorString())
reply.deleteLater()
else:
print(self.client.errorString())
def on_btnWrite(self):
writeUnit :QModbusDataUnit = QModbusDataUnit(QModbusDataUnit.RegisterType.HoldingRegisters,0,3)
#
# value:int = int(self.lineEdit.text())
# writeUnit.setValue(0,value) #写入单个寄存器
writeUnit.setValues([23,4,67]) #写入多个寄存器
reply = self.client.sendWriteRequest(writeUnit,1)
if reply:
while not reply.isFinished():
QCoreApplication.processEvents()
if reply.error()==QModbusDevice.Error.NoError:
QMessageBox.information(self, "tips", "写入成功")
else:
QMessageBox.information(self, "tips", f"写入失败:+{reply.errorString()}")
reply.deleteLater()
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Window()
win.show()
sys.exit(app.exec())
文章评论