HMI
Qt Modbus with TCP/IP connection

In this blog, I would like to provide a small Qt-Quick application (qml) as an example for a Modbus connection via TCP/IP.

In the Qt examples, I only found QWidget examples for Modbus connections, and after recently creating a Qt Quick application for this purpose, I would like to provide a scaled-down version of it as an example.

Test environment

In order to be able to test the application, you need a Modbus server or a program that "simulates" such a server. I used "Modbus Server Pro" from http://www.apphugs.com/modbus-server.html for this. You can use it to run through all the required scenarios.

## Qt application

A quick note in advance: Since it would be too much to post the whole code here, I will make the whole code available as a ZIP file (see below).

Settings

First I created a simple SettingsDialog class that contains the connection options. In the simplified example, this is only the "modbusServerUrl", the "responseTime" and the "numberOfRetries".

    struct Settings {
        QString modbusServerUrl = "192.168.2.86:1502";
        int responseTime = 1000;
        int numberOfRetries = 3;
    };

The names are – I think – self-explanatory.

  • modbusServerUrl = the TCP/IP-number plus Modbus-Server-Port, e.g., 192.168.2.86:502

  • responseTime = the maximum time in ms for which the server waits for a response

    • numberOfRetries = the number of failed attempts that are accepted.

    Application

onConnectButtonClicked()

With the onConnectButtonClicked() function, the connection data is read from the settings file and the connection to the Modbus server is established.

onReadButtonClicked()

With onReadButtonClicked(), various readRequests are then initiated, and the corresponding registers are read from the Modbus server. The returned values are passed on to qml as Q_PROPERTY via emit signals and updated in the user interface.

Write function

The onWriteButtonClicked(int writeregister) function is used for writing to the Modbus server register. This allows for various registers to be written on the Modbus server via the "writeregister" variable.

You can download the application here: ix-modbus-tcp-example.zip.