
Introduction
This article explains a Modbus TCP common driver class. This class implements a modbus TCP master driver.
It supports the following commands:
- Read coils
- Read discrete inputs
- Write single coil
- Write multiple cooils
- Read holding register
- Read input register
- Write single register
- Write multiple register
Background
I haven’t explained how the modbus protocol works in detail, because there is plenty of information around.
Using the code
All commands can be sent in synchronous or asynchronous mode. If a value is accessed in synchronous mode, the program will stop and wait for the slave to response. If the slave doesn't answer within a specified time, a timeout exception is called. The class uses multi-threading for both synchronous and asynchronous access. The class creates two communication lines for each slave. This is necessary because the synchronous thread has to wait for a previous command to finish. This would block the asynchonous connection if we don't use a separate line. The class directory contains a help file (ModbusClassTCP\doc) with detailed information for every function.
There is an example application included that shows the basic features. It contains all functions in asynchronous mode. The synchronous functions are similar. The sample has some additional code to make the results and handling more comfortable. It has a timer included that generates a watchdog telegram for the Modbus slave I use for testing. You can disable this watchdog, or modify it for your needs.
Points of Interest
Remember that a lot of Modbus clients use a watchdog telegram to make sure the master is still alive. If you don’t call this watchdog within a specified time, the slave will no longer set any output.
History