Academic Program

Lab Exercise 17: Unions

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 Project Main_Open_Project.png icon on the main toolbar

Navigate to the folder where you saved the exercise files for this class.

Click on the Lab17.X folder.

Select Open Project OpenProjectButton.png.
 

Open C Source File

Lab17.png

 

Open the Lab17.c source file from the project tree by double clicking on its icon.

This will bring up Lab17.c in a window to edit

 

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 Project Main_Debug_Project.png button. This will build and send the program to the simulator.
Click on the Continue Debug_Continue.png button. This begins the simulation which will stop at line 73.

Open the Variables window (Shift + Alt + 1) and expand the variables as below.

Lab17Results.png

 

Click on the Step Over button Debug_Step_Over.png several times.

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 Session Debug_Finish_Debugger_Session.png button.

Close 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).