QModbusClient的案列

首先连接到服务端:

QModbusTcpClient *client = new QModbusTcpClient(); client->setConnectionParameter(QModbusDevice::NetworkAddressParameter, “192.168.100.1”); client->setConnectionParameter(QModbusDevice::NetworkPortParameter, 8008); client->connectDevice();

这样就连接上服务端了,下面可以发送请求了

发送读或写请求到服务端

写请求:

QModbusDataUnit writeUnit(QModbusDataUnit::HoldingRegisters, 40003, 1); // write 1 value in address 40003 writeUnit.setValue(0, 0x253); //这里先建好QModbusDataUnit if (auto *reply = client->sendWriteRequest(writeUnit, 1)) //发送写请求 { if (!reply->isFinished()) { connect(reply, &QModbusReply::finished, this, [this, reply]() { if (reply->error() != QModbusDevice::NoError) // error in reply reply->deleteLater(); }); } else { if (reply->error() != QModbusDevice::NoError) // error in reply // broadcast replies return immediately reply->deleteLater(); } } else { // error in request }
<

读请求:

QModbusDataUnit readUnit(QModbusDataUnit::InputRegisters, 40006, 1); // just read input register 40006 if (auto *reply = client->sendReadRequest(readUnit, 255)) // client id 255 { if (!reply->isFinished()) { // connect the finished signal of the request to your read slot connect(reply, &QModbusReply::finished, this, &YourClass::readReady); } else { delete reply; // broadcast replies return immediately } } else { // request error } YourClass::readReady { QModbusReply *reply = qobject_cast<QModbusReply *>(sender()); if (!reply) return; if (reply->error() == QModbusDevice::NoError) { const QModbusDataUnit unit = reply->result(); int startAddress = unit.startAddress(); // the start address, here 40006 int value = unit.value(0); // value of the start address + 0 … } else { // reply error } reply->deleteLater(); // delete the reply }
<

免责声明:文章内容来自互联网,本站不对其真实性负责,也不承担任何法律责任,如有侵权等情况,请与本站联系删除。
转载请注明出处:QModbusClient的案列 https://www.yhzz.com.cn/a/15944.html

上一篇 2023-05-13
下一篇 2023-05-13

相关推荐

联系云恒

在线留言: 我要留言
客服热线:400-600-0310
工作时间:周一至周六,08:30-17:30,节假日休息。