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 Lab 16 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.
Software Tools
Tool | About | Installers |
Installation
Instructions |
||
---|---|---|---|---|---|
Windows | Linux | Mac OSX | |||
MPLAB® X
Integrated Development Environment |
| | | | |
MPLAB® XC16
C Compiler |
| | | | |
Exercise Files
File | Download |
Installation
Instructions |
||
---|---|---|---|---|
Windows | Linux | Mac OSX | ||
Project and Source Files
|
| | | |
Procedure
1
Open the Project
Start MPLAB® X IDE, then click on the Open Project icon on the main toolbarNavigate to the folder where you saved the exercise files for this class.
Click on the LAB16.X folder.
Select Open Project .2
Debug Project
Click on the Debug Project button. This will build and send the program to the simulator.5
Set a Breakpoint
Open the Variables Window ( Alt + shift + 1) and expand bitByte and bitField as shown here.
Click the Step Into button to execute line 47. Line 47 writes a value of 0x55 to the fullByte member of the variable bitByte. Note that the bitField members also changed appropriately to reflect the new value of 0x55 = 0b01010101.bitByte.fullByte = 0x55;
6
7
8
9
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.