How to create and use enums in Arduino
A guide on declaring standard enums with enumeration constants as well as enums and constants that live within a namespace in Arduino (C++).
We recommend that you clone our Open Source Arduino Starter Project, checking out the main branch and carrying out the steps below. The changes can be found on the tutorial/enums branch.
git clone git@github.com:delasign/arduino-starter-project.git
We recommend using option two as it leads to higher readability, integrity and ease of maintenance.
Please note that if you wish to use the same name for enumeration constants in different enums (i.e. Value_1 being used in two enums Sample and SampleTwo), you must declare your enums and enumeration constants under different namespaces.
This solution can be found below under option two.
Option One: Standard Enums
This option gives you the option of using enums as if they were values (i.e. an integer with a unique name).
Please note that this means that two enums cannot use the same enumeration constant name (i.e. EnumA { Value _1 } and EnumB { Value_1 } cannot exist within the same file).
If you are seeking to create a solution that uses the same name for the enumeration constant of different enums, consult option two.
Declare the Enum
Declare the enum in the project.
Use the Enum
To use the enum, either call the value directly (i.e. Value_1) or call the value through the enum object (i.e. Sample::Value_1).
Please note that if you have declared the enum in a separate file, you must include the header declaration at the top of your .ino or .cpp file.
Option Two: Enums with a Namespace
Declare the Enum
In your project, declare a namespace and within it declare the enum value.
Please note that enums must have unique names, even if they are under separate namespaces.
Use the Enum
To use the enum, either call the namespace followed by the value (i.e. NameSpace::EnumName::Value_1) or call the namespace, followed by the enum and value (i.e. NameSpace::EnumName::Value_1).
Please note that if you have declared the enum in a separate file, you must include the header declaration at the top of your .ino or .cpp file.
Looking to learn more about things you can do with Arduino?
Search our blog to find educational content on Arduino.