Using libmodbus Backend

Libmodbus is a free software library to send/receive data according to the Modbus protocol. Libmodbus only supports TCP and serial port connections.

Creating Modbus Devices

At first it is necessary to check that QModbus provides the desired backend:

foreach (const QByteArray &backend, QCanBus::instance()->plugins()) {
    if (backend == "libmodbus") {
        // were found

Where, libmodbus is the backend name.

Further, it is necessary to request from QModbus the device with the active libmodbus interface. As libmodbus device may be either client or server device, you have to choose between QModbus::createServer() and QModbus::createClient() as appropriate:

QModbusServer *server = QModbus::createServer("libmodbus");


QModbusClient *client = QModbus::createClient("libmodbus");

For every server, tables must be initialized before connecting it to the network. Next example will set up every table to be size of ten values. Maps can also be not set at all, in that case they will be size zero. Value of every field is initialized to zero.

modbusServer->setMap(QModbusDevice::DiscreteInputs, 10);
modbusServer->setMap(QModbusDevice::Coils, 10);
modbusServer->setMap(QModbusDevice::InputRegisters, 10);
modbusServer->setMap(QModbusDevice::HoldingRegisters, 10);

Before connection each device must also be given a connection to the network. Remember that libmodbus only supports serial port and tcp. Application data unit (ADU) is the package type specified for the connection type. Generally serial port uses QModbusDevice::RemoteTerminalUnit adu and tcp uses QModbusDevice::TCP adu.

QSerialPort *serialPort = new QSerialPort("ttyS0");
modbusServer->setDevice(serialPort, QModbusDevice::RemoteTerminalUnit)

Reading and writing with a client device can be done either with single field at once or by bigger block of adjacent fields. If you try to read/write a list of QModbusDataUnits that are not adjacent to each other read/write will be unsuccessful.

QList<QModbusDataUnit> units;
units.append(QModbusDataUnit(QModbusDevice::HoldingRegisters, 3, 0x1af5));
units.append(QModbusDataUnit(QModbusDevice::HoldingRegisters, 4, 0x1001));
units.append(QModbusDataUnit(QModbusDevice::HoldingRegisters, 5, 0xff34));

© 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.