possible to define variable as bit?

I'd like to switch between 2 states each time a function runs. The best way I can think of doing this is using a bit variable and incrementing it at the end of the function, but it seems one can't define a bit variable in arduino like in C.

Whats the next cleanest way to do this? Incrementing if its 0 and decrementing if its 1 seems pretty cumbersome.

void FlippyFunction( void )
{
  static boolean state = false;  // or "= true;"

  if ( state )
  {
    // Your code goes here
  }
  else
  {
    // Your other code goes here
  }
  state = ! state;
}

similarly,

byte toggle = 0;

then
toggle = 1-toggle; // results in 1-0-1-0-1-0...

neither worked, I'm not sure what exactly is going on but state or toggle were not changing from the value one using serial.println.

I ended up continuously incrementing an unsigned int and using modulus : if (state % 2); state++;

I'd like to switch between 2 states each time a function runs

You are using static or global memory, aren't you?

The best way I can think of doing this is using a bit variable

The only way of getting a single bit is to use bit fields in a struct. If you've only got one such variable, you may as well use a whole byte.

neither worked, I'm not sure what exactly is going on

Neither are we, unless you post some code.

I ended up continuously incrementing an unsigned int and using modulus : if (state % 2); state++;

try: byte state = (state+1) % 2 ; // 0 <-> 1

Real bitfields are only possible in structs
struct
{
byte b:1;
} x;

this defines the var x.b which is 1 bit in size but still uses 8 bits in memory. Advantage is that if you need more you can do:

struct
{
byte a:1;
byte b:1;
byte c:1;
} x;

which still uses 1 byte until the sum of the sizes exceeds 8, then it will allocate 2 bytes

1 Like