Objective
This demo illustrates the use enumerations to create a list of constant labels that may be used in conjunction with variables declared with the enum’s type. The primary purpose of enumerations is to make your code more readable and easier to maintain.
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 Lab18.X folder.
Select Open Project .2
Debug Project
Click on the Debug Project button. This will build and send the program to the simulator.Click on the Continue button. This begins the simulation.Wait for the UART 1 Output window to finish printing.
Click on the Halt button.
Results
3
End Debug Session
End the Simulation Session by clicking the Finish Debugger Session button.Clear out the UART 1 Output window (Ctrl + L)
Close the Project.
Conclusions
Enumerations provide a means to associate a list of constants with one or more variables. Theoretically, these constants represent the entire range of valid values for the variable. Some compilers will enforce this range (compile time only - runtime checking is up to you). However, even if the compiler doesn’t do any checking, by sticking to the list of valid constants it becomes more difficult to accidentally assign an invalid value.
Perhaps the greatest benefit of using enumerations is that they make your code more readable by replacing “magic numbers” and that it becomes much easier to maintain. If you need to add additional valid values, you need only add them to the enum list. If the value of some of the labels change, you may not have to change the rest of your code to reflect the changes (depending on how you have written your code).