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 到地址 0
if (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();
}