Easy-to-use Python driver for the PCA9536 GPIO expander.
Forked from rogiervandergeer/pca9536-driver.
This fork removes the smbus2 dependency and communicates directly with the Linux /dev/i2c-N
character device, making it suitable for embedded Linux systems without PyPI access.
Copy the pca9536/ package directory to your project or onto the target system. No external
dependencies are required.
PYTHONPATH=src python3 -m pytestInitialise the device by passing the I2C bus number. The bus can be specified as:
- an integer:
1resolves to/dev/i2c-1 - a device path:
"/dev/i2c-1" - a sysfs path containing
i2c-N:"/sys/bus/i2c/devices/i2c-1"
from pca9536 import PCA9536
with PCA9536(bus=1) as device:
...The address of the PCA9536 defaults to 0x41. If needed it can be overridden:
PCA9536(bus=1, address=0x42)Before opening the device you can check whether it is present on the bus:
device = PCA9536(bus=1)
if device.probe():
...You can also probe a different bus or address:
if device.probe(bus=3):
...The PCA9536 has four GPIO pins, which are represented by PCA9536Pin objects that can be accessed by using index brackets:
pin = device[0]If desired, you can loop over all pins:
for pin in device:
...Reading the logic level of the pin is done with the read() method, which returns a boolean:
logic_level = pin.read()To switch the pin to output mode and write the logic level:
from pca9536 import PinMode
pin.mode = PinMode.output # or use "output"
pin.write(True)Note that writing only sets the output flip-flops of the GPIO expander, and has therefore no effect when the pin is in input mode.
If you have the need to read from, write to or set the mode of multiple pins simultaneously,
then you can use the respective methods and properties of the PCA9536 object.
Reading returns a tuple of four booleans:
pin_0, pin_1, pin_2, pin_3 = device.read()Writing can be done to one or more pins at the same time:
device.write(pin_0=True, pin_2=False)Setting the same mode of all pins to the same value:
device.mode = PinMode.inputor specify a value per pin by providing a tuple of four values:
device.mode = PinMode.input, Pinmode.output, "input", NoneNote that also here the values PinMode.input and PinMode.output may be used interchangeably with the strings
"input" and "output". Providing None for any of the values will leave the mode of the respective pin unchanged.
The PCA9536 offers functionality to invert the polarity of the input bits. Note that the outputs are not affected by this setting.
Polarity inversion of a single pin can be enabled by:
pin.polarity_inversion = TruePolarity inversion of all pins can be set at the same time in a similar manner to that of the pin mode:
device.polarity_inversion = False
# or
device.polarity_inversion = False, True, True, Nonewhere None will leave the current polarity inversion of a pin untouched.