Objective
This lab is designed to help you to understand how to work with unions. The code is very short and performs no practical function, but it will enable you to work with a union variable and observe how it makes use of data memory when values are written to its members.
Note that you will be using the simulator a bit differently this time. Rather than simply running and stopping your code to see the results, you will be setting breakpoints at three points in your code, and stopping at each of them to observe the data in the watch window.
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
Open the Project
Start MPLAB® X IDE, then click on the Open ProjectNavigate to the folder where you saved the exercise files for this class.
Click on the Lab17.X folder.
Select Open Project
.Edit Source File
Set breakpoints as instructed on lines 73 and 82 by clicking on the line number in the left column.
Edit the code from lines 96 to 104 according to the comments.
Debug Project
Once you finish writing the code:
Click on the Debug ProjectClick on the Continue
Open the Variables window (Shift + Alt + 1) and expand the variables as below.

Observe the changes in the Variable Window after each time an instruction is executed. You should notice when one item is changed all the items in the union are affected.
Results
If your code was correct, then you should have seen the values shown in each of the steps above.
Code Analysis
(NOTE: Line numbers correspond to those in the provided solution file.)
Lines 18-61
This is the union variable declaration for AccumulatorA and AccumulatorB
Line 72
STEP 1: This line assigns a value to the long member of AccumulatorA
Line 82-85
STEP 2: This line assigns a value to the long member of AccumulatorA
Line 96
STEP 3: Creates a variable AccB of type AccumulatorB
Line 98
STEP 3: Clears AccB
End Debug Session
End the Simulation Session by clicking the Finish Debugger SessionClose the Project.
Conclusions
- Unions allow the same memory location to be viewed and manipulated as different data types.
- They make it possible to store different variable types in the same memory location(s).
