Created
May 8, 2023 12:35
-
-
Save Io-Maciek/19b9b1efdb759f9a344ff2e88dfd51a8 to your computer and use it in GitHub Desktop.
(Python) A class representing a PCF8574 I2C I/O expander chip.
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
class PCF8574: | |
"""A class representing a PCF8574 I2C I/O expander chip.""" | |
def __init__(self, i2c, address): | |
""" | |
Initializes a new PCF8574 instance. | |
Args: | |
i2c: The I2C bus the device is connected to. | |
address: The I2C address of the device. | |
""" | |
self._i2c=i2c | |
self._address=address | |
def _pin_to_integer(self, p0=None, p1=None, p2=None, p3=None, p4=None, p5=None, p6=None, p7=None): | |
""" | |
Converts pin states to an integer value representing a byte. | |
Args: | |
p0-p7: The state of each pin. Leave as None to ignore, or set to True or False to check. | |
Returns: | |
An integer value representing the state of each pin as a byte. | |
""" | |
byte_value = 0x00 | |
if p0 is not None and p0: | |
byte_value |= 0x01 | |
if p1 is not None and p1: | |
byte_value |= 0x02 | |
if p2 is not None and p2: | |
byte_value |= 0x04 | |
if p3 is not None and p3: | |
byte_value |= 0x08 | |
if p4 is not None and p4: | |
byte_value |= 0x10 | |
if p5 is not None and p5: | |
byte_value |= 0x20 | |
if p6 is not None and p6: | |
byte_value |= 0x40 | |
if p7 is not None and p7: | |
byte_value |= 0x80 | |
return int(byte_value) | |
def set_pin_state(self, p0=None, p1=None, p2=None, p3=None, p4=None, p5=None, p6=None, p7=None): | |
""" | |
Sets the state of the specified pins. | |
Args: | |
p0-p7: The state of each pin. Leave as None to ignore, or set to True or False to set the state. | |
""" | |
self._i2c.writeto(self._address, bytearray([self._pin_to_integer(p0, p1, p2, p3, p4, p5, p6, p7)])) | |
def get_pin_state(self, p0=None, p1=None, p2=None, p3=None, p4=None, p5=None, p6=None, p7=None): | |
""" | |
Gets the state of the specified pins. | |
Args: | |
p0-p7: The state of each pin. Leave as None to ignore, or set to True or False to check. | |
Returns: | |
True if the specified pins are set, otherwise False. | |
""" | |
i = self._pin_to_integer(p0, p1, p2, p3, p4, p5, p6, p7) | |
return self._i2c.readfrom(self._address, 1)[0] & i == i | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment