How to set bits in a byte variable (Arduino)

My question will be specific to Arduino, although if you know how to do this in C, it will also be similar to the Arduino IDE.

So, I have 5 integer variables:

r1, r2, r3, r4, r5

Their value is 0 (off) or 1 (on). I would like to store them in a byte variable, let the relay call it, not by adding them, but setting certain bits to 1/0 regardless of whether they are 0 or 1. For example:

1, 0, 0, 0, 1

I would like to have the same value in my byte byte variable, not r1 + r2 + r3 + r4 + r5, which in this case will be decimal 3, binary 11.

Thank!

+3
source share
2 answers

UNION . . . .

union {
  uint8_t BAR;
  struct {
    uint8_t  r1 : 1; // bit position 0
    uint8_t  r2 : 2; // bit positions 1..2
    uint8_t  r3 : 3; // bit positions 3..5
    uint8_t  r4 : 2; // bit positions 6..7 
    // total # of bits just needs to add up to the uint8_t size
  } bar;
} foo;

void setup() {
  Serial.begin(9600);
  foo.bar.r1 = 1;
  foo.bar.r2 = 2;
  foo.bar.r3 = 2;
  foo.bar.r4 = 1;

  Serial.print(F("foo.bar.r1 = 0x"));
  Serial.println(foo.bar.r1, HEX);
  Serial.print(F("foo.bar.r2 = 0x"));
  Serial.println(foo.bar.r2, HEX);
  Serial.print(F("foo.bar.r3 = 0x"));
  Serial.println(foo.bar.r3, HEX);
  Serial.print(F("foo.bar.r4 = 0x"));
  Serial.println(foo.bar.r5, HEX);

  Serial.print(F("foo.BAR = 0x"));
  Serial.println(foo.BAR, HEX);
}

UNION

. uint8_t .

, .. . .

+2

:

char byte = (r1 << 4) | (r2 << 3) | (r3 << 2) | (r4 << 1) | r5;

:

char byte = r1 | (r2 << 1) | (r3 << 2) | (r4 << 3) | (r5 << 4);
+1

All Articles