White Papers
7
The following source code example implements three functions to set the direction, set and read the level of a specific GPIO pin.
#define TCA9555_REG_INPUT 0
#define TCA9555_REG_OUTPUT 2
#define TCA9555_REG_DIRECTION 6
#define GPIO_MODE_OUTPUT 1
#define GPIO_MODE_INPUT 2
int gpio_pin_set_direction(int pin, int dir)
{
__u16 bmp;
int rc = smbus_read_word(fd, TCA9555_REG_DIRECTION, &bmp);
if ( rc )
return rc;
if ( dir == GPIO_MODE_INPUT )
bmp |= 1 << chip_pin;
else if ( dir == GPIO_MODE_OUTPUT )
bmp &= ~(1 << chip_pin);
rc = smbus_write_word(fd, TCA9555_REG_DIRECTION, bmp);
return rc;
}
int gpio_pin_set_level(int pin, int level)
{
__u16 bmp;
int rc = smbus_read_word(fd, TCA9555_REG_OUTPUT, &bmp);
if ( rc )
return rc;
if ( level )
bmp |= 1 << chip_pin;
else
bmp &= ~(1 << chip_pin);
rc = smbus_write_word(fd, TCA9555_REG_OUTPUT, bmp);
return rc;
}
int gpio_pin_get_level(int pin, int *level)
{
__u16 bmp;
int rc = smbus_read_word(fd, TCA9555_REG_INPUT, &bmp);
if ( !rc )
*level = !!(bmp & (1 << chip_pin));
return rc;
}