How to Use Enum in Arduino: Simple Guide with Examples
In Arduino, use
enum to create a list of named integer constants that make your code easier to read and manage. Define an enum with names for values, then use those names in your code instead of numbers.Syntax
An enum groups related named integer constants under one type. You start with the keyword enum, give it a name, and list the names inside curly braces. Each name represents a number starting from 0 by default.
Example parts:
enum: keyword to define the groupStatus: the name of the enum type{ OFF, ON, ERROR }: named constants inside the enum
arduino
enum Status {
OFF, // 0
ON, // 1
ERROR // 2
};Example
This example shows how to define an enum for LED states and use it to control an LED on pin 13. It prints the current state to the Serial Monitor.
arduino
enum LedState {
OFF,
ON,
BLINK
};
LedState currentState = OFF;
void setup() {
pinMode(13, OUTPUT);
Serial.begin(9600);
}
void loop() {
switch (currentState) {
case OFF:
digitalWrite(13, LOW);
Serial.println("LED is OFF");
currentState = ON;
break;
case ON:
digitalWrite(13, HIGH);
Serial.println("LED is ON");
currentState = BLINK;
break;
case BLINK:
digitalWrite(13, HIGH);
delay(250);
digitalWrite(13, LOW);
delay(250);
Serial.println("LED is BLINKING");
currentState = OFF;
break;
}
delay(1000);
}Output
LED is OFF
LED is ON
LED is BLINKING
LED is OFF
LED is ON
LED is BLINKING
...
Common Pitfalls
Common mistakes when using enum in Arduino include:
- Not ending the enum definition with a semicolon
;. - Using enum names without specifying the enum type variable.
- Assuming enum values start at 1 instead of 0.
- Assigning values outside the enum without casting.
Always remember to declare variables of the enum type to use the named constants properly.
arduino
/* Wrong: missing semicolon */ enum Color { RED, GREEN, BLUE }; // <-- added semicolon here /* Right: with semicolon */ enum Color { RED, GREEN, BLUE }; /* Wrong: using enum names without variable */ // digitalWrite(13, RED); // error /* Right: declare variable */ Color ledColor = RED; // digitalWrite(13, ledColor); // works if ledColor matches pin logic
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Define enum | Create named integer constants | enum Mode { AUTO, MANUAL, OFF }; |
| Default values | Start at 0, increment by 1 | AUTO=0, MANUAL=1, OFF=2 |
| Assign custom values | Set specific numbers | enum Mode { AUTO=1, MANUAL=5, OFF=10 }; |
| Use enum variable | Store enum values | Mode current = AUTO; |
| Switch with enum | Control flow with enum | switch(current) { case AUTO: ... } |
Key Takeaways
Use
enum to name related integer constants for clearer Arduino code.Always end enum definitions with a semicolon
;.Enum values start at 0 by default but can be set manually.
Declare variables of the enum type to use the named constants properly.
Use enums in
switch statements for clean control flow.