Interfacing the PCF8574 port expander with a RasPi

Controling the pins

According to the specifications of the datasheet, the PCF8574 can source (i.e. give out during HIGH pin state) max. 300 μA, but it can sink (i.e. accept during LOW pin state) 20 milliamps. Thus, if you want to control some LEDs with the PCF8574, you have to connect them this way:

+5V—— +LED ——- Resistor —— P0-P7

This is called ‘sinking’ current, rather than ‘sourcing’ it. At power-on the I/Os of PCF8574 are set to HIGH, i.e. the LED will be off. For turning the LEDs on, you have to pull the respective pin (P0-P7) LOW.

The PCF8574 can be easily controlled using Gordon Henderson’s wiringPi2 library.  If you prefer Python, you may wan’t to try Phillip Howard’s wiringPi2-python which can be downloaded from github:

$ git clone https://github.com/Gadgetoid/WiringPi2-Python

Build and installation instructions can be found in the README file. The example below turns a LED connected to P0 on – and turns it off after  five seconds. Pins A0 to A2 of PCF8574 are in H, L, L, state (see table above), which corresponds to the I2C hex address 0x21. The pinBase can be any number above 64, i.e. P0 will be ’65’, P1, ’66’, P2, ’67’ and so forth.

#!/usr/bin/python

import wiringpi2 as wp

pinBase = 65 
# P0 -> 65
# P1 -> 66
# ...
# P7 -> 72
# second pcf8574
# P0 -> 73
# ...

i2c_addr1 = 0x21
#i2c_addr2 =

wp.wiringPiSetup()
wp.pcf8574Setup(pinBase, i2c_addr1)
#wp.pcf8574Setup(pinBase + 16, i2c_addr1)

LED = pinBase + 0

# 1 -> OUTPUT, 0 -> INPUT
wp.pinMode(LED, 1)

# 1 -> HIGH, 0 -> LOW 
wp.digitalWrite(LED, 0) # LED on
wp.delay(5000)
wp.digitalWrite(LED, 1) # LED off