Electronic – ‘bit’ type for AVR Microcontroller programming

avr-gccc

I have written a code for 8051 microcontroller, where I used bit type, something like this:

static bit done_flag = 0;    /* bit variable */

bit testfunc (               /* bit function */
  bit flag1,                 /* bit arguments */
  bit flag2)
{
.
.
.
return (0);                  /* bit return value */
}

Now I am porting this to ATmega16 AVR controller. I found that there is no support for
bit type in AVR.

AVR-lib C User Manual says:

� Data types: char is 8 bits, int is 16 bits, long is 32 bits, long
long is 64 bits, float and double are 32 bits (this is the only
supported floating point format), pointers are 16 bits (function
pointers are word addresses, to allow addressing up to 128K program
memory space). There is a -mint8 option (see Options for the C
compiler avr-gcc) to make int 8 bits, but that is not supported by
avr-libc and violates C standards (int must be at least 16 bits). It
may be removed in a future release.

So what should I do now?

Best Answer

You can use a struct like this:

typedef struct {
    uint8_t bit0:1;
    uint8_t bit1:1;
    uint8_t bit2:1;
    uint8_t bit3:1;
    uint8_t bit4:1;
    uint8_t bit5:1;
    uint8_t bit6:1;
    uint8_t bit7:1;
} BitField;

typedef union {
    BitField asBits;
    uint8_t asByte;
} BitByte;

BitByte mBitField; 

And to access one bit at once you only have to

mBitField.asBits.bit3 = 1