Qtmodbus之串口模式写操作

Posted 沧海一笑-dj

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Qtmodbus之串口模式写操作相关的知识,希望对你有一定的参考价值。

00. 目录

01. 概述

Qt中几个常用的串口modbus类

QModbusRtuSerialSlave       //modbus串口通信方式下的服务器类
QModbusRtuSerialMaster      //串口通信方式下的客户端类
QModbusServer               // QModbusServer类接收和处理modbus的请求。
QModbusDataUnit             //存储接收和发送数据的类,数据类型为1bit和16bit
QModbusReply                //客户端访问服务器后得到的回复(如客户端读服务器数据时包含数据信息)

02. 开发环境

Windows系统:Windows10

Qt版本:Qt5.15或者Qt6

Pro配置文件如下

QT       += core gui serialbus serialport

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \\
    main.cpp \\
    widget.cpp

HEADERS += \\
    widget.h

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

03. 写Coils程序示例

widget.h文件

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

//前向声明
class QModbusClient;
class QModbusReply;


class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();


private:
    QModbusClient *modbusDevice = nullptr;


private slots:
    void onReadReady();
};
#endif // WIDGET_H

widget.cpp文件

#include "widget.h"
#include <QModbusRtuSerialMaster>
#include <QModbusDataUnit>
#include <QModbusReply>
#include <QVariant>
#include <QSerialPort>
#include <QDebug>

//构造函数
Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    //1. 创建QModbusDevice对象
    modbusDevice = new QModbusRtuSerialMaster;

    //2. 如果处于连接状态,则断开连接
    if (modbusDevice->state() == QModbusDevice::ConnectedState)
    {
        //断开连接设备
        modbusDevice->disconnectDevice();
    }

    //3. 设置串口相关参数
    //设置串口信息
    modbusDevice->setConnectionParameter(QModbusDevice::SerialPortNameParameter, QVariant("COM3"));
    //设置校验 无校验
    modbusDevice->setConnectionParameter(QModbusDevice::SerialParityParameter, QSerialPort::NoParity);
    //设置波特率
    modbusDevice->setConnectionParameter(QModbusDevice::SerialBaudRateParameter, QSerialPort::Baud19200);
    //设置停止位
    modbusDevice->setConnectionParameter(QModbusDevice::SerialStopBitsParameter, QSerialPort::OneStop);
    //设置数据位
    modbusDevice->setConnectionParameter(QModbusDevice::SerialDataBitsParameter, QSerialPort::Data8);

    //4. 设置其他信息
    //设置超时时间
    modbusDevice->setTimeout(1000); //1秒
    //设置失败重试次数
    modbusDevice->setNumberOfRetries(3);

    //5. 连接到设备
    bool ok = modbusDevice->connectDevice();
    if (!ok)
    {
        qDebug() << "连接到串口失败: " << modbusDevice->errorString();
    }
    else
    {
        qDebug() << "连接到串口成功";
    }

    //6. 发送写请求
    //从地址0开始写10个保持寄存器的值
    //QModbusDataUnit writeData(QModbusDataUnit::HoldingRegisters, 0, 10);

    //从地址0开始写10个线圈的值
    QModbusDataUnit writeData(QModbusDataUnit::Coils, 0, 10);
    for (int i = 0; i < writeData.valueCount(); i++)
    {
        writeData.setValue(i, (i * i) % 2);
    }

    qDebug() << "发送的数据为: " << writeData.values();

    QModbusReply* reply = modbusDevice->sendWriteRequest(writeData, 1);
    if (reply)
    {
        if (!reply->isFinished())
        {
            //接收响应信息
            connect(reply, &QModbusReply::finished, this, [this, reply](){
                if (reply->error() == QModbusDevice::ProtocolError)
                {
                    //接收到的响应信息是协议错误
                    qDebug() << "写入数据错误:" << reply->errorString();
                }
                else if (reply->error() != QModbusDevice::NoError)
                {
                    //接收到的响应消息是其它错误
                    qDebug() << "写入数据错误: " << reply->errorString();
                }
                else
                {
                    //接收到的消息没有错误 一般没有必要解析响应消息
                    const QModbusDataUnit data = reply->result();

                    qDebug() << "消息数据个数:" << data.valueCount() << " :" << data.values();

                }

                reply->deleteLater();
            });
        }
        else
        {
            //发送没有响应数据
            //broadcast replies return immediately
            reply->deleteLater();
        }
    }
    else
    {
        qDebug() << "sendWriteRequest Error: " << reply->errorString();
    }


    //7. 发送读取数据请求
    //从地址0开始读取10个保持寄存器的值
    //QModbusDataUnit data(QModbusDataUnit::HoldingRegisters, 0, 10);
    //从地址0开始读取10个离散输入量的值
    //QModbusDataUnit data(QModbusDataUnit::DiscreteInputs, 0, 10);

    //QModbusDataUnit::Coils 从地址0开始读取10个线圈值
    QModbusDataUnit data(QModbusDataUnit::Coils, 0, 10);

    //QModbusDataUnit::InputRegisters 从地址0开始读取10个输入寄存器的值
    //QModbusDataUnit data(QModbusDataUnit::InputRegisters, 0, 10);

    reply = modbusDevice->sendReadRequest(data, 0x1);
    if (nullptr == reply)
    {
        qDebug() << "发送请求数据失败: " << modbusDevice->errorString();
    }
    else
    {
        if (!reply->isFinished())
        {
            connect(reply, &QModbusReply::finished, this, &Widget::onReadReady);
        }
        else
        {
            //broadcast replies return immediately
            delete reply;
        }
    }

}


//析构函数
Widget::~Widget()
{
    if (modbusDevice)
    {
        modbusDevice->disconnectDevice();
    }

    delete modbusDevice;
}

//准备读取数据的槽函数
void Widget::onReadReady()
{
    auto reply = qobject_cast<QModbusReply*>(sender());
    if (nullptr == reply)
    {
        return;
    }

    //判断是否出错
    if (reply->error() == QModbusDevice::NoError)
    {
        //读取响应数据
        const QModbusDataUnit responseData = reply->result();

        qDebug() << "读到数据为:" << responseData.values();

    }
    else if (reply->error() == QModbusDevice::ProtocolError)
    {
        qDebug() << "Read response Protocol error: " << reply->errorString();
    }
    else
    {
        qDebug() << "Read response Error: " << reply->errorString();
    }


    //删除reply
    reply->deleteLater();
}


执行结果

20:32:27: Starting D:\\ProgramData\\Qt\\build-Test-Desktop_Qt_5_15_2_MinGW_32_bit-Debug\\debug\\Test.exe ...
连接到串口成功
发送的数据为:  QVector(0, 1, 0, 1, 0, 1, 0, 1, 0, 1)
消息数据个数: 10  : QVector(0, 1, 0, 1, 0, 1, 0, 1, 0, 1)
读到数据为: QVector(0, 1, 0, 1, 0, 1, 0, 1, 0, 1)
20:34:02: D:\\ProgramData\\Qt\\build-Test-Desktop_Qt_5_15_2_MinGW_32_bit-Debug\\debug\\Test.exe exited with code 0

04. 写HoldingRegisters程序示例

widget.h文件

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

//前向声明
class QModbusClient;
class QModbusReply;


class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();


private:
    QModbusClient *modbusDevice = nullptr;


private slots:
    void onReadReady();
};
#endif // WIDGET_H

widget.cpp文件

#include "widget.h"
#include <QModbusRtuSerialMaster>
#include <QModbusDataUnit>
#include <QModbusReply>
#include <QVariant>
#include <QSerialPort>
#include <QDebug>

//构造函数
Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    //1. 创建QModbusDevice对象
    modbusDevice = new QModbusRtuSerialMaster;

    //2. 如果处于连接状态,则断开连接
    if (modbusDevice->state() == QModbusDevice::ConnectedState)
    {
        //断开连接设备
        modbusDevice->disconnectDevice();
    }

    //3. 设置串口相关参数
    //设置串口信息
    modbusDevice->setConnectionParameter(QModbusDevice::SerialPortNameParameter, QVariant("COM3"));
    //设置校验 无校验
    modbusDevice->setConnectionParameter(QModbusDevice::SerialParityParameter, QSerialPort::NoParity);
    //设置波特率
    modbusDevice->setConnectionParameter(QModbusDevice::SerialBaudRateParameter, QSerialPort::Baud19200);
    //设置停止位
    modbusDevice->setConnectionParameter(QModbusDevice::SerialStopBitsParameter, QSerialPort::OneStop);
    //设置数据位
    modbusDevice->setConnectionParameter(QModbusDevice::SerialDataBitsParameter, QSerialPort::Data8);

    //4. 设置其他信息
    //设置超时时间
    modbusDevice->setTimeout(1000); //1秒
    //设置失败重试次数
    modbusDevice->setNumberOfRetries(3);

    //5. 连接到设备
    bool ok = modbusDevice->connectDevice();
    if (!ok)
    {
        qDebug() << "连接到串口失败: " << modbusDevice->errorString();
    }
    else
    {
        qDebug() << "连接到串口成功";
    }

    //6. 发送写请求
    //从地址0开始写10个保持寄存器的值
    QModbusDataUnit writeData(QModbusDataUnit::HoldingRegisters, 0, 10);
    for (int i = 0; i < writeData.valueCount(); i++)
    {
        writeData.setValue(i, i * i);
    }

    qDebug() << "发送的数据为: " << writeData.values();

    QModbusReply* reply = modbusDevice->sendWriteRequest(writeData, 1);
    if (reply)
    {
        if (!reply->isFinished())
        {
            //接收响应信息
            connect(reply, &QModbusReply::finished, this, [this, reply](){
                if (reply->error() == QModbusDevice::ProtocolError)
                {
                    //接收到的响应信息是协议错误
                    qDebug() << "写入数据错误:" << reply->errorString();
                }
                else if (reply->error() != QModbusDevice::NoError)
                {
                    //接收到的响应消息是其它错误
                    qDebug() << "写入数据错误: " << reply->errorString();
                }
                else
                {
                    //接收到的消息没有错误 一般没有必要解析响应消息
                    const QModbusDataUnit data = reply->result();

                    qDebug() << "消息数据个数:" << data.valueCount() << " :" << data.values();

                }

                reply->deleteLater();
            });
        }
        else
        {
            //发送没有响应数据
            //broadcast replies return immediately
            reply->deleteLater();
        }
    }
    else
    {
        qDebug() << "sendWriteRequest Error: " << reply->errorString();
    }


    //7. 发送读取数据请求
    //从地址0开始读取10个保持寄存器的值
    QModbusDataUnit data(QModbusDataUnit::HoldingRegisters, 0, 10);
    //从地址0开始读取10个离散输入量的值
    //QModbusDataUnit data(QModbusDataUnit::DiscreteInputs, 0, 10);

    //QModbusDataUnit::Coils 从地址0开始读取10个线圈值
    //QModbusDataUnit data(QModbusDataUnit::Coils, 0, 10);

    //QModbusDataUnit::InputRegisters 从地址0开始读取10个输入寄存器的值
    //QModbusDataUnit data(QModbusDataUnit::InputRegisters, 0, 10);

    reply = modbusDevice->sendReadRequest(data, 0x1);
    if (nullptr == reply)
    {
        qDebug() << "发送请求数据失败: " << modbusDevice->errorString();
    }
    else
    {
        if (!reply->isFinished())
        {
            connect(reply, &QModbusReply::finished, this, &Widget::onReadReady);
        }
        else
        {
            //broadcast replies return immediately
            delete reply;
        }
    }

}


//析构函数
Widget::~Widget()
{
    if (modbusDevice)
    {
        modbusDevice->disconnectDevice();
    }

    delete modbusDevice;
}

//准备读取数据的槽函数
void Widget::onReadReady()
{
    auto reply = qobject_cast<QModbusReply*>(sender());
    if (nullptr == reply)
    {
        return;
    }

    //判断是否出错
    if (reply->error() == QModbusDevice::NoError)
    {
        //读取响应数据
        const QModbusDataUnit responseData = reply->result();

        qDebug() << "读到数据为:" << responseData.values();

    }
    else if (reply->error() == QModbusDevice::ProtocolError)
    {
        qDebug() << "Read response Protocol error: " << reply->errorString();
    }
    else
    {
        qDebug() << "Read response Error: " << reply->errorString();
    }


    //删除reply
    reply->deleteLater();
}



执行结果

20:23:23: Starting D:\\ProgramData\\Qt\\build-Test-Desktop_Qt_5_15_2_MinGW_32_bit-Debug\\debug\\Test.exe ...
连接到串口成功
发送的数据为:  QVector(0, 1, 4, 9, 16, 25, 36, 49, 64, 81)
消息数据个数: 10  : QVector(0, 1, 4, 9, 16, 25, 36, 49, 64, 81)
读到数据为: QVector(0, 1, 4, 9, 16, 25, 36, 49, 64, 81)
20:23:29: D:\\ProgramData\\Qt\\build-Test-Desktop_Qt_5_15_2_MinGW_32_bit-Debug\\debug\\Test.exe exited with code 0

05. 综合示例

程序界面

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-J2Oiv0Co-1621479015968)(assets/image-20210520104421393.png)]

settingdialog.h文件

#ifndef SETTINGDIALOG_H
#define SETTINGDIALOG_H

#include <QDialog>
#include <QtSerialPort>

namespace Ui {
class SettingDialog;
}

//串口设置相关类
class SettingDialog : public QDialog
{
    Q_OBJECT

public:
    struct Settings
    {
        //串口名
        QString serialName = "COM3";
        //校验位
        int parity = QSerialPort::NoParity;
        //波特率
        int baud = QSerialPort::Baud19200;
        //数据位
        int dataBits = QSerialPort::Data8;
        //停止位
        Qtmodbus之串口模式读操作

Qtmodbus之TCP模式读操作

串口之CreateFile 函数具体解释

C#上位机开发一:串口通讯之如何制作一个串口调试助手

代码调试之串口打印

跪求msp430的串口发送程序啊!