Syntax - how to read which pins are HIGH

Hi,

I am reading the state of PCF8574 pins like this:

byte expanderRead() {
  byte _data;
  Wire.requestFrom(expander, 1);
  if(Wire.available()) {
    _data = Wire.receive();
  }
  
  return _data;
}

When:
P0 is HIGH I get 1
P1 is HIGH I get 2
P2 is HIGH I get 4
P3 is HIGH I get 8
.
.
.
P1 and P2 are HIGH I get 3

When only one pin is HIGH there is no problem - only 8 combinations.
When more pins are HIGH there is a problem - 256 combinations.
I need to create an array with all combinations!

Is there a simple method to read which pins are HIGH?

Thanks for help!

Why do you need an array with all the combinations? You can tell which pins are high by looking at which bits of your byte are set (i.e. are 1).

if (_data & 1)
// P0 is set

if (_data & 2)
// P1 is set

if (_data & 4)
// P2 is set

...

if (_data & 128)
// P7 is set

  • Ben

Why do you need an array with all the combinations? You can tell which pins are high by looking at which bits of your byte are set (i.e. are 1).

if (_data & 1)
// P0 is set

That is what I was looking for.
I do not know C and that's why I could not do that.
Tell me please how should I understand that: (_data & 1) // OK I already know....

And now, other way. I have 8 variables:

p1 = 1;
p2 = 1;
p3 = 0;
p4 = 0;
.
.
How to tell PCF8574 taht these pins (1,2,3,4) should be like 1,1,0,0....?

Thanks!

You can use logical OR to combine the bits, or very simply, just add the correct value corresponding to the bits in question. That value is always a power of 2, of course. So, bit 0 is 2^0 which is 1, bit 1 is 2^1, which is 2, bit 2 is 2^2 which is 4, and so on.

Turning bits 1, 3 and 4 on would be 2 + 8 + 16 = 26. You can set or clear specific bits with a combination of AND and OR operations. Exclusive OR (XOR) can be handy as well.