FYI accessing single bits

First off I am in no way an expert like those who are >10K posters.
I thought some might be interested in how to access individual bits in memory.
In some sketches, I use single bits as a flag bits to enable or disable processes.
One use of this method is you can read the 16 bits into an integer, let us call it “temp”.
You have now saved your current process status.
Next, you zero all the bits.
This disables up to 16 processes.
Later, you write “temp” back where it came form, returning process status.

This is similar to:
uint8_t oldSREG = SREG;
. . .
SREG = oldSREG;

Below bit 13 is set (1) the rest are reset (0)

typedef struct {
byte flag0:1;  //  bit 0 --
byte flag1:1;  //  bit 1  |
byte flag2:1;  //  bit 2  |
byte flag3:1;  //  bit 3  |
byte flag4:1;  //  bit 4  >  1st byte
byte flag5:1;  //  bit 5  |
byte flag6:1;  //  bit 6  |
byte flag7:1;  //  bit 7 --
byte flag8:1;  //  bit 8  0 --
byte flag9:1;  //  bit 9  1  |
byte flag10:1; //  bit 10 2  |
byte flag11:1; //  bit 11 3  |
byte flag12:1; //  bit 12 4  > 2nd byte
byte flag13:1; //  bit 13 5  |
byte flag14:1; //  bit 14 6  |
byte flag15:1; //  bit 15 7 --
} 
MyFlags; //packs 16 flag bits in two bytes
//**************** 
MyFlags Flags =  {
//Bits positions on an Arduino UNO
//LSB         MSB  LSB         MSB
//0 1 2 3 4 5 6 7  8 9 1 1 1 1 1 1
//                     0 1 2 3 4 5
  0,0,0,0,0,0,0,0, 0,0,0,0,0,1,0,0};  //Two bytes

//********************************************
// Method to print the 16 flag bits
// Use unsigned integer to get two bytes
unsigned int value = 0;    
// Copy the two bytes where the bits are stored
 memcpy(&value, &Flags, 2); 
// Print the 16 flag bits
Serial.println(value,BIN); 
delay(1000);
//********************************************

Example of bit access:

Flags.flag0 = true; //enable the process
Flags.flag0 = 1; //enable the process
. . .
if (Flags.flag0 == true)
if (Flags.flag0)
{
//do something
~~ Flags.flag0 = false; //disable the process~~
Flags.flag0 = 0; //disable the process
}

I'm a bit worried about this:

if (Flags.flag0 == true)

The flags aren't booleans so comparing them to a boolean is a bit dodgy. However this is OK:

if (Flags.flag0)

Thanks Nick.

The proper way would be to use:
if (Flags.flag0 )
if (!Flags.flag0)

.

That is correct.

I generally don't like tests of the form:

bool foo;

if (foo == true) ...

Even for booleans, because the whole point of an "if" is to be taken if the test is true*. So checking for "== true" is redundant. You may as well say:

  • Is it raining?
  • Is it true it is raining?
  • Is it true it is true it is raining?
  • Is it true it is true it is true it is raining?
  • Is it true it is true it is true it is true it is raining?
  • Is it true it is true it is true it is true it is true it is raining?

Where does the madness stop?


  • Perhaps more strictly, if the test evaluates to non-zero, however my main point still stands.

When it stops raining, of course.