Bit fields

Using Bit Fields in C/C++ is a great way to keep your code organized in robotics. Since most interfaces with hardware involve reading registers or single bit(s) within registers, they make the code easier to read, and it makes it easier to change the code if the hardware interface changes.

The best way to explain using bit fields is by example, so I will use a really basic example with 3 different LEDs, but this can apply to any digital piece of hardware.

Example
The 3 LEDs are Red, Green, and White. Outputting HIGH on the pin (logic 1) turns on the LED, and LOW (logic 0) turns the LED off. The LEDs are on pins 3, 4, and 6 of an 8-bit port, respectively. To setup a bit field, we'll use a union of structures:

When reading or writing to the 8-bit port register of the microcontroller, the BOT_LEDs_Byte_Field struct is used, while modifying a single LED uses the BOT_LEDs_Bit_Field struct. Here is an example usage of the above interface: (Assume the PORTB variable is the port register on the microcontroller, defined in the microcontrollers include file)

At first this does not seem all that useful, but for more advanced interfaces such as buses with more than one bit in the bit field, it becomes much more useful, and the entire hardware interface can be described in one union with multiple ports. If one of the pins changes on one of the LEDs, only the bit field structure needs to be changed, and the rest of the code can remain untouched.

Pitfalls
Bit fields can not have members extending past the compiler's bit size. For example in an 8-bit compiler for a microcontroller, You can not have a bit fields with 5 bits, then 5 more bits, then 6 bits, you must have 5 bits, then 3 bits, then 2 bits, then 6 bits, since members of a structure are not guaranteed to be aligned in memory.

= Resources =
 * Bit fields on Wikipedia
 * Unions on Wikipedia
 * Structs on Wikipedia