Lab Exercise 16: Bit Fields
Objective
This demo illustrates the use of bit fields. There is no code for you to write. All you need to do is build and run the project and observe the results. The code itself combines what we learned in a previous lab about unions, with the concept of bit fields to create a variable that will allow us to access it as a full byte, or as individual bits.
Reference Materials
Exercise Files
Procedure
Open the Project
Start MPLAB® X IDE, then click on the Open Project icon on the main toolbar.
Navigate to the folder where you saved the exercise files for this class.
Click on the LAB16.X folder.
Select Open Project .
Debug Project
Click on the Debug Project button. This will build and send the program to the simulator.
Set a Breakpoint
Set a breakpoint on line 47 by clicking on the line number in the gray margin. (Alternatively, right-click on the line and select “Toggle Line Breakpoint”). You should then see a small red square replace the line number:
Continue
Click on the Continue button to run until the breakpoint.
Set a Breakpoint
Open the Variables Window ( Alt + shift + 1) and expand bitByte and bitField as shown here.
Execute One Line of Code
Click the Step Into button to execute line 47. Line 47 writes a value of 0x55 to the fullByte member of the variable bitByte.
Click the Step Into button 
Click the Step Into button 
Click the Step Into button 
End Debug Session
End the Simulation Session by clicking the Finish Debugger Session button.
Close the Project.
Conclusions
Bit fields allow us to efficiently use individual bits for Boolean values or as flags/semaphores. On the various PIC® architectures, setting and clearing a bit field variable in C will make use of the very efficient bit set and bit clear instructions in assembly language. However, other operations may generate more code than would be necessary if you were working with a full 16-bit integer type variable. So, bit fields can be invaluable in some circumstances, but they should be used with care so that excess code will not be generated.