Modbus for the Raspberry Pi

11.4.2013

Some very basic code to communicate with a Raspberry Pi over the Modbus protocol.

Description

The Raspberry Pi is a sweet little computer with surprisingly good I/O capabilities. In physics proprietary control hardware utilizing modbus can cost several hundred dollars for essentially the same hardware capability as the Pi. I started some code to allow communications with the Pi over modbus (as have others). Perhaps with enough interest, momentum can develop to the point where the Pi can be a good building block for lab systems.

What I've written so far is available on Github, released under the MIT License. There are a few components described below.

Libraries

The modbus protocol is standardized serial communications protocol (see Wikipedia and Modbus). The code I've written is based on the the open-source libmodbus.

For communications on the Pi, I've used the free and open-source WiringPi library.

Server

The server is essentially a layer between libmodbus (acting as a server) and WiringPi for communicating with the hardware. The capabilities are extremely limited at the moment, this is really only a demo. The server code would require some pretty serious work before being used in a real application. The server also outputs information to the console (not in a sophisticated way, just with std::cout).

Client

The client connects to the server using libmodbus. The example program is written for a configuration with 5 LEDs wired to some of the output pins. The program counts in binary in the following loop:

```C++ for(int i=0; i < exp2(nb); i++) { // set pins using bitwise logic for(addr = ADDRESS_START; addr <= ADDRESS_END; addr++) { int j = addr - ADDRESS_START; modbus_write_register(ctx, addr, (i & (int)exp2(j)) ); }

    // wait 500ms
    std::chrono::milliseconds dura( 500 );
    std::this_thread::sleep_for( dura );
}

```

which could be easily modified. Obviously this is not a complex client program.

GPIO Test

I also wrote a brief GPIO test, which flashes the LEDs using WiringPi as a test of the system. I had five LEDs wired to the Pi during this.

Conclusions

A simple start. I'd be happy for anybody to fork the repo and use it is a starting point. If you make any useful modifications, please send a pull request!