您的位置:首页 > 财经 > 金融 > Qt工业物联网

Qt工业物联网

2024/11/16 4:09:44 来源:https://blog.csdn.net/weixin_38241876/article/details/141192547  浏览:    关键词:Qt工业物联网

Qt中的Modbus通信指南:QModbusClient与QModbusServer类解析 (qq.com)

#include <QCoreApplication>
#include <QModbusTcpServer>
#include <QUrl>int main(int argc, char *argv[]) {QCoreApplication app(argc, argv);QModbusTcpServer modbusServer;// 初始化数据模型,这里我们只设置了一个保持寄存器QModbusDataUnitMap dataModel;dataModel.insert(QModbusDataUnit::HoldingRegisters, { QModbusDataUnit::HoldingRegisters, 0, 10 });modbusServer.setDataMap(dataModel);const QUrl url = QUrl::fromUserInput("127.0.0.1:502");modbusServer.setConnectionParameter(QModbusDevice::NetworkPortParameter, url.port());modbusServer.setConnectionParameter(QModbusDevice::NetworkAddressParameter, url.host());if (!modbusServer.listen()) {qFatal("Unable to start the Modbus server: %s", qPrintable(modbusServer.errorString()));}return app.exec();
}

#include <QCoreApplication>
#include <QModbusTcpClient>
#include <QModbusReply>int main(int argc, char *argv[]) {QCoreApplication app(argc, argv);QModbusTcpClient modbusClient;modbusClient.setConnectionParameter(QModbusDevice::NetworkPortParameter, 502);modbusClient.setConnectionParameter(QModbusDevice::NetworkAddressParameter, "127.0.0.1");if (!modbusClient.connectDevice()) {qFatal("Unable to connect to the Modbus server.");}// 构建一个写请求QModbusDataUnit writeUnit(QModbusDataUnit::HoldingRegisters, 0, 1);writeUnit.setValue(0, 42); // 写入值 42 到地址 0if (auto *reply = modbusClient.sendWriteRequest(writeUnit, 1)) { // 1 是服务器地址if (!reply->isFinished()) {QObject::connect(reply, &QModbusReply::finished, [&]() {if (reply->error() == QModbusDevice::NoError) {qDebug("Write success.");// 构建一个读请求QModbusDataUnit readUnit(QModbusDataUnit::HoldingRegisters, 0, 1);if (auto *readReply = modbusClient.sendReadRequest(readUnit, 1)) {if (!readReply->isFinished()) {QObject::connect(readReply, &QModbusReply::finished, [readReply]() {if (readReply->error() == QModbusDevice::NoError) {const QModbusDataUnit unit = readReply->result();qDebug("Read success: %d", unit.value(0));} else {qWarning("Read error: %s", qPrintable(readReply->errorString()));}readReply->deleteLater();});} else {delete readReply; // broadcast reply returns immediately}}} else {qWarning("Write error: %s", qPrintable(reply->errorString()));}reply->deleteLater();});} else {delete reply; // broadcast reply returns immediately}}return app.exec();
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com