-
Notifications
You must be signed in to change notification settings - Fork 163
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
examples: add an example PCF8574 script
- Loading branch information
1 parent
e99e76b
commit 03d7559
Showing
1 changed file
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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) |