diff --git a/examples/i2c-pcf8574.py b/examples/i2c-pcf8574.py new file mode 100644 index 000000000..f4f481555 --- /dev/null +++ b/examples/i2c-pcf8574.py @@ -0,0 +1,59 @@ +""" +this serves as an example script. connect a PCF8574 to the glasgow, and run the +following command: + + glasgow run-script i2c-pcf8574.py i2c-initiator -V 3.3 --pin-scl 0 --pin-sda 1 + +this will configure the I/O pins as Outputs, and will present a walking 1-bit logic +low, with the other pins high... connect 8x LEDs with resistor from Vcc to +demonstrate +""" + +import asyncio + +class PCF8574: + """ + a quasi-bidirectional I/O expander + """ + def __init__(self, iface, addr=0): + self.iface = iface + + assert addr in range(8) + self.addr = 0x20 | ( addr & 0x7 ) + + async def _read(self): + p = await self.iface.read(self.addr, 1, stop=True) + if p is None: + raise Exception("I2C NAK") + return p[0] + + async def read(self, mask=0xff): + # in order to read pins, we must set them to "high"... but don't disturb + # other pins that may have a set value if we're not interested in them + p = await self._read() + await self.write(p | mask) + + p = await self._read() + return p & mask + + async def write(self, p): + # "high" bits have acceleration on their rising edge, then a ~100uA pullup + # "low" bits are driven low + success = await self.iface.write(self.addr, [ p ], stop=True) + if not success: + raise Exception("I2C NAK") + + +io = PCF8574(iface, 0) + +# read the I/O pin values +print("0x{:02X}".format(await io.read())) + +# write a walking 1-bit low pattern +for i in range(8): + p = ~(1 << i) + await io.write(p) + await asyncio.sleep(0.5) + +# power down the device after use +await device.set_voltage("AB", 0)