Lab Exercise 17: Unions

Last modified by Microchip on 2023/11/09 09:21

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.

Reference Materials

Exercise Files

Procedure

Open the Project

Start MPLAB X IDE, then click on the Open Project Open Main Project button 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 Open Project Button


Open C Source File

Lab17.c file in project file tree

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 Debug Main Project button button. This will build and send the program to the simulator.

Click on the Continue Debug Continue button button. This begins the simulation which will stop at line 73.Open the Variables window (Shift + Alt + 1) and expand the variables as shown in the accompanying image.

Variables window with union variables expanded


Step Over Code to the Next Breakpoint

Click on the Step Over button Debug Step Over button 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 Finish Debugger Session button 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).