Using Bitfields in C programming we can access individual bits of a memory location. Bitfields in microcontroller programming can be used to declare register structures and get access to individual bits of the microcontroller registers.

These bitfields can be grouped to form a field of any size needed. Suppose a register field which selects an ADC channel is 3-bit wide then you can declare a field which is 3-bits in size and use it easily.

For example.,

If you want to declare a 8bit register with one-2bit bitfield, one-3bit bitfield, one-1bit bitfield, then the code will be,

// declaration

typedef union

{

    unsigned char Byte;

    struct

    {

         unsigned char bit012 : 3;

         unsigned char bit34 : 2;

         unsigned char bit5 : 1;

         unsigned char bit6 : 1;

         unsigned char bit7 : 1;

     }bits;

}registerType;

// define a pointer and cast it to point to the registers memory location

registerType *pReg = (registerType*)0x00008000;

// use the fields as

pReg->bits.bit5 = 1;

pReg->bits.bit012 = 7;

// access the whole byte as

pReg->Byte = 0x55;

The above example is for a little endian microcontroller, If your microcontroller is a big endian microcontroller then the higher bit fields should be declared first. However todays compilers are smart enough to take care of the endianness of the microcontroller.




About the Author

is the author of this blog and is an Embedded systems design engineer by profession & Founder @ Valetron Systems Pvt Ltd


Email:This email address is being protected from spambots. You need JavaScript enabled to view it.

Find us on Google+

HIRE ME FOR YOUR PROJECT AS A FREELANCER

 

EasyEDA: Free Circuit Design Software

  • Easy Schematic Capture
  • Powerful Circuit Simulation
  • Online PCB design

Design Your Circuit and PCB here:

https://easyeda.com/editor

Cheap PCB Manufacturing

Electronic Components Online Store