MODBUS on the Pi Part 3, Interfacing with IO’s

Previously MODBUS on the Pi Part 2, Adding functionality for testing

In Parts 1 and 2 we created a working MODBUS controller that we can talk to, now we want to interface with the real world!

The following link shows how to access the GPIO using c code http://elinux.org/RPi_Low-level_peripherals#GPIO_Driving_Example_.28C.29.
I was using the examples provided to add the GPIO functionality to my program, but it was not documented clearly enough, so I decided to try something else. I am glad I did, WiringPi.com provides a great way to deal with many different IO expansion boards for the PI. I installed it according to the instructions on the site and it worked perfectly!

I was able to replace a ton of redundant code with one line, fantastic!

#include   // WAY easier method to access Pi IO functions.  Thanks to WiringPi.com!

Now to set up the PIN I chose for reading the digital IO, I can simply insert this code near the top of the main() function.

... end of variable declarations
    int nPin5Value = 0; // for reading Pin5 switch value

    // allow user override of port number, this is done so I can run multiple instances on different ports with a bash script
    if( argc > 1 )
    {
	nPort = atoi(argv[2]);
    }

    // new code to initialize the Pi IO and set Physical Pin 5 to be an input.
    wiringPiSetupPhys();
    pinMode(5,INPUT);

...

    for(;;) {
        uint8_t query[MODBUS_TCP_MAX_ADU_LENGTH];

        // new code

	int nTempPin5 = digitalRead(5);
	if( nTempPin5 != nPin5Value )
	{
 	    nPin5Value = nTempPin5;
	    printf("Pin 5 : %d\n",nPin5Value); // show the change in Pin 5 on the console for debugging

	    // now update the register I want to use for Pin 5 (why not use bit 5 for pin 5? that would be easy to remember)
            mb_mapping->tab_bits[5] = nPin5Value;
	}

Now the only thing we need to do is add the wiringpi library to the compile command:
gcc -Wall -I /usr/include/modbus modserv.c -o modserv -L/usr/lib/modbus -lmodbus -lwiringPi
Then to run it you need to use sudo, because the low level access to hardware requires it.
sudo ./modserv

Here is the latest source code.
Click here for the sourcecode for modserv.c Part 3