Skip to content

Libmodbus on Raspberry pi

Stéphane Raimbault edited this page Jul 16, 2024 · 11 revisions

Raspberry Pi has gained popularity in recent days and a lot of enthusiasts / hobbyist would like to implement libmodbus on RPi to host a modbus master / slave. Here is “how to install libmodbus” guide on RPi (Raspbian).

1) Installing dependancies.

sudo apt-get install -y autoconf libtool

2) Clone libmodbus master branch by,

git clone https://github.com/stephane/libmodbus/

3) Enter the directory.

cd libmodbus

4) ./autogen.sh && ./configure --prefix=/usr && make && sudo make install

5) To test the libmodbus, try examples under tests folder.

To compile code, use gcc filename.c -o filename $(pkg-config --libs --cflags libmodbus)

Additional notes :

If you’re using linux distros (other than debian based), such as Arch Linux or PiDora, you must use relevant package manager options in step #1. (like pacman or yum)

In order to use native RPi serial port for RTU mode, you MUST disable serial console by using sudo raspi-config as it conflicts with modes RTU communication.

Native serial port is listed as ttyAMA0 under /dev/ directory.

If you’re using UART to RS485 chip like 75176 or anything similar, you would like to check the libmodbus raspberry pi fork which makes use of a GPIO to enable rx-tx. (Link : https://github.com/dhruvvyas90/libmodbus)

Known issue(s):

  1. While using RPi native UART (/dev/ttyAMA0), RPi sometimes tends to append a null byte once port has been opened and it may result into invalid reply. (As per this issue link : https://github.com/stephane/libmodbus/issues/302).

You may want to use modbus_flush(ctx) after modbus_connect call just to ensure that byte is flushed. If problem persists, you may try OP's mothod of modifying modbus-rtu.c and recompile to make it effective.

Related PR not merged

  1. Using /sys/class/gpio/: https://github.com/stephane/libmodbus/pull/439/commits/7f7a5c4e82992ca737bdfa1af3cfb3bd7c5f42e6