Search code examples
c++craspberry-pii2c

Experience writing C-code for PCF8575 I/O-Expander on Raspberry Pi


Has anyone attempted to write a C/C++ routine to expand the I/O on a Raspberry PI using the PCF8575 I/O-Expander from SparkFun?

I can find a lot of Python samples, which don't help me a lot since I need to develop in C.

I have everything configured right, and I know that my I2C device responds. For example I can do this from the command line:

i2cset -y 1 0x20 0xff 0xff
i2cset -y 1 0x20 0x00 0x00

and all 16 Outputs (in this case) will turn on/off

I also know I could simply do the system(); function from within my C-code, but that is not the way I want to go about this, as I'd like to be able to address single Bits in that word and later do toggle modes, etc etc.

I took a look at the Arduino implementation and their sample code, which is (of course) all based on the Atmel processors and modifying all the libraries and files to be compliant with the ARM processor might bring me way beyond the deadline of my project. (It is a simple project to show the difference between populating regular I/O on the Pi, vs using I/O expander via I2C to save I/Os) I'm also writing on a tutorial for my personal reference and for anyone who is interested. But I'm stuck at this point.

Please help


Solution

  • With regard to addressing individual bits and changing modes: you can't. The PCF8575 is a very simple I/O expander, and only supports two operations:

    1. Writing two bytes to set the state of all pins.

    2. Reading two bytes to read the state of all pins. Pins are put into a quasi-input state (with pullup) if they're set high.

    There is no way to change the state of one pin without writing to all other pins in the process, and there is no explicit input state for pins. If you want fancy features like that, you'll need a fancier I/O expander. :)


    Now, that all being said, there is a way to read and write to I2C devices, such as this I/O expander, without shelling out to the i2cset command. Specifically, if you're working in C, you can read and write to the I2C device node to communicate with a device. Documentation on how to do this is available as part of the Linux kernel, at:

    https://www.kernel.org/doc/Documentation/i2c/dev-interface