Create byte to send to MCP23017 from boolean tests

Hi,

I need to send a byte to an MCP23017 to activate a series of relays based upon the results of some boolean tests that compare input conditions from other inputs. How does one efficiently create a byte from these boolean tests

e.g. True, False, False, False, False, False, True, False >> 10000010

Thanks, Jeff

This is a tad clunky, but it’s the first thing that came to mind:

#define BIT8  7
#define BIT7  6
#define BIT6  5
#define BIT5  4
#define BIT4  3
#define BIT3  2  
#define BIT2  1
#define BIT1  0

byte byteToSend;


void setup() {
  int testVal;
  Serial.begin(9600);

  byteToSend = 0;
  
  PackByte(BIT4, true);       // Send: 00001010 (= 10 DEC)
  PackByte(BIT2, true);

  Serial.println(byteToSend);
}

void PackByte(int whichBit, int whichState)
{
  byteToSend |= whichState << whichBit;
}

void loop() {
}

Making use of bitfields is an options

struct BITS
{
  byte b1: 1;
  byte b2: 1;
  byte b3: 1;
  byte b4: 1;
  byte b5: 1;
  byte b6: 1;
  byte b7: 1;
  byte b8: 1;
};

void setup() {

  Serial.begin(9600);
}

void loop() {

  union
  {
    BITS logic;
    byte value;
  } bits;

  bits.logic.b1 = false;
  bits.logic.b2 = true;
  bits.logic.b3 = false;
  bits.logic.b4 = false;
  bits.logic.b5 = false;
  bits.logic.b6 = false;
  bits.logic.b7 = false;
  bits.logic.b8 = true;

  Serial.println(bits.value, HEX);
}

You can directly set the bits in the struct from your logic. The union allows access to either the bit form or the byte form.

econjack:

void PackByte(int whichBit, int whichState)

{
 byteToSend |= whichState << whichBit;
}

This only works for true. It won’t strike a bit with false.

Because true OR false = true.

To make it work for both true and false, do this:

void PackByte(int whichBit, int whichState)
{
  if (whichState)
    byteToSend |= 1 << whichBit;
  else
    byteToSend &= ~(1 << whichBit);
}

Because true AND NOT true is false.

@Jobi-Wan: You are correct.

Thank you all, I will poke around with these and see what happens.