Go Down

Topic: possible to define variable as bit? (Read 711 times) previous topic - next topic

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.

Coding Badly

Code: [Select]
void FlippyFunction( void )
{
 static boolean state = false;  // or "= true;"

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

CrossRoads

similarly,

byte toggle = 0;

then
toggle = 1-toggle; // results in 1-0-1-0-1-0...
Designing & building electrical circuits for over 25 years.  Screw Shield for Mega/Due/Uno,  Bobuino with ATMega1284P, & other '328P & '1284P creations & offerings at  my website.

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++;

AWOL

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

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

Quote
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.
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

PaulS

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

Neither are we, unless you post some code.

robtillaart

Quote
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

Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy