Qt实现MODBUS通讯

widget.h

cpp 复制代码
#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

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

html 复制代码
<?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

cpp 复制代码
#include "widget.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}

python代码实现,有个问题暂时未解决。。。。

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)
        try:
            self.client.connectDevice()
        except Exception as e:
            print(e)


    def on_btnRead(self):
        unit:QModbusDataUnit = QModbusDataUnit(QModbusDataUnit.RegisterType.HoldingRegisters,0,1)
        reply:QModbusReply = self.client.sendReadRequest(unit,1)
        # reply.finished.connect(self.get_data)
        if reply:
            if not reply.isFinished():
                reply.finished.connect(self.get_data)
                return


    def on_btnWrite(self):
        ...

    def get_data(self):

        reply: QModbusReply = QModbusReply()

        unit = reply.result()
        reply.deleteLater()

        if (unit.valueCount() > 0):
            print(unit.value(0))
            #todo


















if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = Window()
    win.show()
    sys.exit(app.exec())
相关推荐
可峰科技7 分钟前
斗破QT编程入门系列之二:认识Qt:编写一个HelloWorld程序(四星斗师)
开发语言·qt
全栈开发圈11 分钟前
新书速览|Java网络爬虫精解与实践
java·开发语言·爬虫
面试鸭15 分钟前
离谱!买个人信息买到网安公司头上???
java·开发语言·职场和发展
小白学大数据16 分钟前
JavaScript重定向对网络爬虫的影响及处理
开发语言·javascript·数据库·爬虫
Python大数据分析@19 分钟前
python操作CSV和excel,如何来做?
开发语言·python·excel
上海_彭彭1 小时前
【提效工具开发】Python功能模块执行和 SQL 执行 需求整理
开发语言·python·sql·测试工具·element
334554321 小时前
element动态表头合并表格
开发语言·javascript·ecmascript
沈询-阿里1 小时前
java-智能识别车牌号_基于spring ai和开源国产大模型_qwen vl
java·开发语言
残月只会敲键盘1 小时前
面相小白的php反序列化漏洞原理剖析
开发语言·php
ac-er88881 小时前
PHP弱类型安全问题
开发语言·安全·php