Introduction: How to Use Modbus With Raspberry Pi

Modbus is a serial communication standard and has become a de facto standard communication protocol and is now a commonly available means of connecting industrial electronic devices. In Modbus RTU and Modbus ASCII RS485 is used as the physical layer. Its possible to use a Raspberry Pi as Master or Slave in Modbus applications, but a RS485 interface is needed. Our RS422 / RS485 Serial HAT is a fully galvanic isolated serial communication HAT designed for use with the Raspberry Pi and the perfect choice for such kind of applications.

The objective of this document is to show how to configure the HAT and the Raspberry Pi to be used for Modbus serial communication.

Check out our instructable about MODBUS & Arduino too!

Step 1: Bill of Material

Step 2: Wiring

The wiring is very simple. You have to connect only the A and B terminals of the HAT with the A and B line of the Modbus system. Y and Z terminals are not used for this kind of application. For long distances it is recommend to use twisted pairs for A and B.

Step 3: DIP Switch Setting

Our RS422/RS485 HAT comes with 3 DIP switch banks. You have to set these DIP switches for Modbus as shown in the picture above.
Switch 1: 1-OFF 2-ON 3-ON 4-OFF

Switch 2: 1-OFF 2-OFF 3-ON 4-ON

Switch 3: 1-OFF or ON* 2-OFF 3-OFF 4-OFF

*Depending of the position of the RS422/RS485 HAT in the Modbus line you have to switch the terminating resistor ON or OFF. Please switch the resistor to ON position only if the HAT is on one end of the bus line. In all other cases switch the terminating resistor OFF:

Step 4: Free Up Serial Line and Enable UART

The easiest way is to use the raspi-config tool to switch the
UART to the GPIO14/15 pins.

  1. take a fresh Raspbian image
  2. sudo raspi-config
  3. goto '5 Interfacing Options'
  4. goto 'P6 Serial'
  5. 'Would you like a login shell to be accessible over serial?' --> NO
  6. 'Would you like the serial port hardware to be enabled?' --> YES
  7. Finish raspi-config
  8. reboot the Raspberry Pi

Now you can access the UART via /dev/serial0

Step 5: Software Python

You will find an easy-to-use and tested Modbus RTU and Modbus
ASCII implementation for Python on:

http://minimalmodbus.readthedocs.io/en/master/inst...

http://minimalmodbus.readthedocs.io/en/master/usag...

Step 6: Software C++

To implement Modbus communication under c++, the use of libmodbus is recommended.

Installation:

sudo apt update
sudo apt install libmodbus-dev


Compilation of the attached demo program:

cc modbusRTU.c -o modbusRTU `pkg-config --cflags --libs libmodbus`


Start the program with:

./modbusRTU