qt.modbus :(客户端)设备未连接

时间:2019-01-07 07:33:13

标签: c++ qt modbus

我正在尝试使用RS485电缆建立从我的PC到PID温度控制器的串行连接。另外,我也使用USB到RS485转换器。我已经在Qt Creator中编写了代码。 “ modbus_rtu.pro”

#-------------------------------------------------
#
# Project created by QtCreator 2019-01-05T10:37:15
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = modbus_rtu
TEMPLATE = app
DEFINES += QT_DEPRECATED_WARNINGS
CONFIG += c++11
QT += serialport
QT += serialbus
SOURCES += \
    main.cpp \
    mainwindow.cpp

HEADERS += \
    mainwindow.h

FORMS += \
    mainwindow.ui

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

“ mainwindow.h”

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();

 private:
 Ui::MainWindow *ui;
 };

#endif // MAINWINDOW_H

“ main.cpp”

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();

return a.exec();
}

“ mainwindow.cpp”

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtSerialPort/QSerialPort>
#include <QVariant>
#include <QtSerialBus/QModbusRtuSerialMaster>
#include <QDebug>
#include <QtSerialPort>

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QModbusRtuSerialMaster *client=new QModbusRtuSerialMaster();
        client->setTimeout(200);
        client->setNumberOfRetries(3);
        client->setConnectionParameter(QModbusDevice::SerialPortNameParameter,"/dev/ttyUSB0");
        client->setConnectionParameter(QModbusDevice::SerialParityParameter,QSerialPort::OddParity);
        client->setConnectionParameter(QModbusDevice::SerialBaudRateParameter,QSerialPort::Baud19200);
        client->setConnectionParameter(QModbusDevice::SerialDataBitsParameter,QSerialPort::DataBits(8));
        client->setConnectionParameter(QModbusDevice::SerialStopBitsParameter,QSerialPort::OneStop);
        client->connectDevice();

QModbusDataUnit readUnit(QModbusDataUnit::HoldingRegisters,00000,8);
 if (auto *reply=client->sendReadRequest(readUnit,1))
  {
      reply->result();
  }
}
MainWindow::~MainWindow()
{
delete ui;
}

在代码编译期间没有错误,但是当我运行此代码时,它显示以下错误:在调试窗口中的qt.modbus: (Client) Device is not connected。谁能告诉我我要去哪里错了?

0 个答案:

没有答案