Applying a bitmask to a command for a PCA9555 I/O expander

I am working with a PCA9555 i/o expander and need to be able to switch outputs on and off at times without affecting existing outputs current state

Here is the portion of the code that is currently being used to turn on a single pin:

#include <Wire.h>

#define PCA9555 0x22                             // 0x22 is address for PCA9555 

#define IN_P0 0x00 // Read Input port0
#define IN_P1 0x01 // Read Input port1
#define OUT_P0 0x02 // Write Output port0
#define OUT_P1 0x03 // Write Output port1
#define CONFIG_P0 0x06 // Configuration port0 configures the direction of the I/O pins 0 is output 1 is input
#define CONFIG_P1 0x07 // Configuration port1 configures the direction of the I/O pins 0 is output 1 is input 

// Initialize
void setup() {
  Serial.begin(9600);                               // start serial comms for Debug 9600 baud
  Wire.begin(PCA9555); // join i2c bus (address optional for master) tried to get working
   write_io (CONFIG_P0, B00000000); //defines all pins on Port0 are outputs
   write_io (CONFIG_P1, B00000000); //defines all pins on Port1 are outputs  
   write_io (OUT_P0, B00000000); //clears all outputs
   write_io (OUT_P1, B00000000); //clears all outputs
  delay(1000);                                       // 
   write_io (OUT_P1, B00000010);   

void loop(){

void write_io(int command, int value){                                    //PCA9555 command processor

So as you can see at this stage I am just turning on one output on the PCA9555.
I am wondering how to “mask” the command so that ONLY the pins I want to change, change when I need to switch other outputs on this chip without affecting the others!

i.e.I am unsure on how to apply a bitmask to my command to say change the output of say P10 of the PCA9555 without affecting the status of P11

Can someone point me in the right direction?

Hello again,

You can use bitSet and bitClear, additionally read this.

Thank you again! :slight_smile:

Sorry for being dumb but I cant work out how I would apply those commands to my example above :frowning:

ie where I want to change JUST the status of P10 to HIGH I would send this:

   write_io (OUT_P1, B00000001);

But or course that would set the current state of P11 to LOW at the same time

Would it be that I need to read the current value (B00000010) then use bitSet() to alter the current value then write that back to the port to achieve (B00000011)?

I need to be able to set and reset these bits at different times in vastly different sections of the code as I have various things tied to all the expander pins that all need switching independently.

Thanks :slight_smile:

Yes, of course you have to know the value first, but, if this value is only changed by your code (if the device doesn't modify this value by itself) then you could just use a variable, named "OUT_P1_currentValue" or whatever... :wink:

Thanks - I'll play :slight_smile: