do you have a flag ?

Here’s  a thing that I’ve never seen explained on the internet although it is very simple to understand and interesting to use. So I hope this could of any help to someone.

When doing microcontroller project,we may need a set of  “software flags” (not generated in hardware) which are basically a set of bits, 1 or 0. Usually one total variable could be used (a byte) to represent true/false but it means that the 7 others bits are left unused which is, in space limited processors, a bit of a waste.

I won’t be talking about “bool” variable. Some C versions don’t allow it, and also sometime it is more useful to have a bunch of related flag grouped together

uint8_t flag_0;
uint8_t flag_1;

//or even fancier :
uint8_t flag[NUMB_OF_FLAGS];

Instead of that, the full length of variable could be used to represent 8 flags (if using a byte, 16 if using a uint16_t and so on…). The flags can be set or reset using bitwise operator with the help of some bitmasks.


#define FLAG_0  0x00000001
#define FLAG_1  0x00000010
#define FLAG_2  0x00000100

uint8_t bank_flag;

//in main or everywhere else, when you want the flag to be set
if(BUTTON_1)       bank_flag |= FLAG_0; // OR operator
else if(BUTTON_2)  bank_flag |= FLAG_1;
else               bank_flag |= FLAG_1;

//to retreive the imformation, one need to AND the byte with the same mask

if(bank_flag & FLAG_0)
{
    PORTB ^= 1<<0; //toogle pin 0 at PORTB

//don't forget to clear the bit, two methods

    bank_flag &= ~ FLAG_0; // AND with the inverse
//Or bit_flip
    bank_flag ^= FLAG_0;
}

It requires you to know about Bitwise operators (it isn’t hard once you’re used to it)
and save quite a bit of space.

Advertisements

Leave a comment

Filed under Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s