Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QModbusTcpClient - How to read input registers of device?



  • Hello,

    I am trying to use modbus the first time.

    I got one modbus device delivering sensor values and this can be used with tcp.

    In python I already managed to query the device.
    All I needed for that were the ip-address, port, input register and number of bytes to read.

    However, in Qt I somehow cannot manage to get this running.

    I would like to read one byte from register 1002.
    I am also wondering what to enter in "sendReadRequest" as second argument. I tried different values without success.

    The following code delivers the following output:

        QVector<quint16> data(1); // One Byte
        QModbusDataUnit adu(QModbusDataUnit::InputRegisters, 1002, data); // Read one byte of register 1002
        QModbusReply *reply = device->sendReadRequest(adu, 3); // What is the second argument for? What do I need there?
        if(reply != nullptr) {
            qDebug() << "Sent read request, state is: " << device->state();
                    qDebug() << reply;
                    qDebug() << "Value 0: " << reply->result().value(0);
                    qDebug() << "Value count: " << reply->result().valueCount();
                    qDebug() << "Input registers:" << reply->result().InputRegisters;
        } else {
            qDebug() << "Send of ready request failed! Error is: " << device->state();
        }
    

    Output:
    Sent read request, state is: QModbusDevice::ConnectedState
    QModbusReply(0x17cce5d00c0)
    Value 0: 0
    Value count: 0
    Input registers: 3

    What am I doing wrong?

    Thank you very much!


  • Lifetime Qt Champion

    @robro said in QModbusTcpClient - How to read input registers of device?:

    What am I doing wrong?

    You're reading the reply just after sending request.
    You should do the reading in a slot connected to https://doc.qt.io/qt-5/qmodbusreply.html#finished



  • Thank you very much!
    Using the "finished"-signal everything works fine :-)


Log in to reply