Structures and Enums in ESP32 Programming
Structures and enumerations are useful C++ features that help you organize data and make ESP32 programs easier to understand.
In an IoT project, you might need to store temperature, humidity, sensor status, device modes, and connection states. Instead of managing many unrelated variables, you can use a struct to group related information and an enum to represent a fixed set of named choices.
In this lesson, you will learn how structures and enumerations work, how to combine them with functions and arrays, and how to use them in practical ESP32 projects.
1. What Is a Structure?
A structure, declared using the struct keyword, is a user-defined type that groups related variables under one name.
For example, a sensor might provide:
- Temperature
- Humidity
- Sensor status
Instead of storing these values in separate variables, you can group them into one structure.
Example Without a Structure
float temperature = 25.5; float humidity = 60.0; bool sensorWorking = true;
These variables describe related information, but they are separate.
Example With a Structure
struct SensorData { float temperature; float humidity; bool sensorWorking; };
The SensorData structure defines a new type that contains three members.
Important: Defining a structure creates a type. It does not automatically create a variable of that type.
2. Creating a Structure Variable
After defining a structure, you can create variables of that type.
struct SensorData { float temperature; float humidity; bool sensorWorking; }; void setup() { Serial.begin(115200); SensorData sensor; sensor.temperature = 25.5; sensor.humidity = 60.0; sensor.sensorWorking = true; Serial.print("Temperature: "); Serial.println(sensor.temperature); Serial.print("Humidity: "); Serial.println(sensor.humidity); Serial.print("Sensor working: "); Serial.println(sensor.sensorWorking ? "Yes" : "No"); } void loop() { }
Explanation
SensorDatais the structure type.sensoris a variable of that type.temperature,humidity, andsensorWorkingare structure members.- The dot operator (
.) accesses a member of a structure variable.
The structure groups the related sensor values together.
3. Initializing a Structure
You can initialize structure members when creating the variable.
struct SensorData { float temperature; float humidity; bool sensorWorking; }; void setup() { Serial.begin(115200); SensorData sensor = {25.5, 60.0, true}; Serial.println(sensor.temperature); Serial.println(sensor.humidity); Serial.println(sensor.sensorWorking); } void loop() { }
The values are assigned to members in the order they are declared.
For clearer initialization in modern C++, you can use designated initializers when supported by your compiler configuration:
SensorData sensor = { .temperature = 25.5, .humidity = 60.0, .sensorWorking = true };
Designated initializers require C++20 support and must follow the member declaration order. If your ESP32 toolchain does not support them, use ordinary aggregate initialization.
4. Accessing and Updating Structure Members
You can read or change individual members using the dot operator.
struct Device { int deviceId; bool isOnline; }; void setup() { Serial.begin(115200); Device device = {101, false}; device.isOnline = true; Serial.print("Device ID: "); Serial.println(device.deviceId); Serial.print("Status: "); Serial.println(device.isOnline ? "Online" : "Offline"); } void loop() { }
This is useful when updating a device's state, sensor readings, or configuration.
5. Structures with Functions
Structures can be passed to functions just like other C++ types.
Example: Display Sensor Data
struct SensorData { float temperature; float humidity; }; void displaySensorData(SensorData data) { Serial.print("Temperature: "); Serial.println(data.temperature); Serial.print("Humidity: "); Serial.println(data.humidity); } void setup() { Serial.begin(115200); SensorData sensor = {28.5, 65.0}; displaySensorData(sensor); } void loop() { }
This function receives a copy of the structure. For small structures, passing by value can be convenient.
For larger structures, or when you do not need to modify the data, a constant reference avoids copying:
void displaySensorData(const SensorData &data) { Serial.println(data.temperature); Serial.println(data.humidity); }
The const SensorData &data parameter lets the function read the original structure without modifying it through that reference.
6. Pointers to Structures
You can also use pointers to access structures.
When you have a pointer to a structure, use the arrow operator (->) to access its members.
struct SensorData { float temperature; float humidity; }; void setup() { Serial.begin(115200); SensorData sensor = {26.5, 58.0}; SensorData *ptr = &sensor; Serial.println(ptr->temperature); Serial.println(ptr->humidity); } void loop() { }
The expression:
ptr->temperature
is equivalent to:
(*ptr).temperature
The pointer must refer to a valid structure object before you access its members.
7. Arrays of Structures
An array of structures lets you store information for multiple sensors or devices.
Example: Multiple Sensor Records
struct SensorData { int sensorId; float temperature; }; SensorData sensors[3] = { {1, 24.5}, {2, 28.0}, {3, 31.2} }; void setup() { Serial.begin(115200); for (int i = 0; i < 3; i++) { Serial.print("Sensor ID: "); Serial.print(sensors[i].sensorId); Serial.print(" | Temperature: "); Serial.println(sensors[i].temperature); } } void loop() { }
Explanation
SensorDatadefines the information stored for each sensor.sensors[3]creates an array with three structure elements.sensors[i].sensorIdaccesses a member of the selected element.- The loop processes all three records.
This approach is useful when monitoring several sensors, storing device information, or maintaining a collection of readings.
8. Nested Structures
A structure can contain another structure as one of its members.
Example: Device Information
struct Location { float latitude; float longitude; }; struct IoTDevice { int deviceId; Location location; bool online; }; void setup() { Serial.begin(115200); IoTDevice device = { 101, {26.8467, 80.9462}, true }; Serial.print("Device ID: "); Serial.println(device.deviceId); Serial.print("Latitude: "); Serial.println(device.location.latitude, 4); Serial.print("Longitude: "); Serial.println(device.location.longitude, 4); Serial.print("Online: "); Serial.println(device.online ? "Yes" : "No"); } void loop() { }
Here, IoTDevice contains a Location structure.
To access a nested member, use the dot operator more than once:
device.location.latitude
Nested structures are useful for organizing device configuration, network information, sensor measurements, and other related data.
9. What Is an Enumeration?
An enumeration, declared with the enum or enum class keyword, represents a set of named values.
Instead of using unexplained numbers for a device's state, you can assign meaningful names to those states.
For example, a smart light may have three operating modes:
- Off
- Manual
- Automatic
Using an enumeration makes these states easier to understand than using numbers such as 0, 1, and 2 throughout the code.
10. Basic Enumeration with enum
Example
enum DeviceMode { MODE_OFF, MODE_MANUAL, MODE_AUTOMATIC }; void setup() { Serial.begin(115200); DeviceMode mode = MODE_AUTOMATIC; if (mode == MODE_AUTOMATIC) { Serial.println("Automatic mode enabled."); } } void loop() { }
Explanation
By default, the enumerators receive integer values starting from zero:
| Enumerator | Default value |
|---|---|
MODE_OFF | 0 |
MODE_MANUAL | 1 |
MODE_AUTOMATIC | 2 |
The variable mode stores one of the named values defined by the enumeration.
The names make the program more readable and reduce the need for unexplained numeric constants.
11. Assigning Values to Enumerators
You can specify the numeric value of an enumerator.
enum DeviceStatus { STATUS_OFFLINE = 0, STATUS_ONLINE = 1, STATUS_ERROR = 10 };
The next enumerator after an explicitly assigned value normally receives the next integer unless you assign a different value.
enum DeviceStatus { STATUS_OFFLINE = 0, STATUS_ONLINE = 1, STATUS_ERROR = 10, STATUS_MAINTENANCE };
Here, STATUS_MAINTENANCE receives the value 11.
Explicit values can be helpful when matching a documented protocol or hardware interface. Do not assume that an enum's numeric values are suitable for transmission or storage unless the format is deliberately defined.
12. Using enum with switch
A switch statement works well with enumerations.
Example: Smart Light Modes
enum LightMode { LIGHT_OFF, LIGHT_MANUAL, LIGHT_AUTOMATIC }; void printLightMode(LightMode mode) { switch (mode) { case LIGHT_OFF: Serial.println("Light mode: OFF"); break; case LIGHT_MANUAL: Serial.println("Light mode: MANUAL"); break; case LIGHT_AUTOMATIC: Serial.println("Light mode: AUTOMATIC"); break; default: Serial.println("Unknown light mode"); break; } } void setup() { Serial.begin(115200); printLightMode(LIGHT_OFF); printLightMode(LIGHT_MANUAL); printLightMode(LIGHT_AUTOMATIC); } void loop() { }
This is more readable than repeatedly comparing numeric values.
An enum-based switch is especially useful for menu systems, operating modes, connection states, and device control logic.
13. Scoped Enumerations with enum class
Modern C++ provides enum class, which creates a scoped enumeration.
Scoped enumerations are generally preferable for new code because their names are contained within the enum's scope and their values do not automatically convert to integers.
Example
enum class DeviceMode { Off, Manual, Automatic }; void setup() { Serial.begin(115200); DeviceMode mode = DeviceMode::Automatic; if (mode == DeviceMode::Automatic) { Serial.println("Automatic mode enabled."); } } void loop() { }
Notice the difference:
DeviceMode::Automatic
The DeviceMode:: prefix identifies which enumeration the value belongs to.
This helps prevent naming conflicts when a project has multiple enums containing similar names.
Comparing enum and enum class
| Feature | enum | enum class |
|---|---|---|
| Scope | Enumerators can enter the surrounding scope | Enumerators are scoped |
| Value access | MODE_OFF | DeviceMode::Off |
| Implicit conversion to integer | Usually allowed | Not allowed |
| Recommended use | Existing code and specific compatibility needs | Most new C++ code |
14. Using enum class with switch
enum class ConnectionState { Disconnected, Connecting, Connected, Error }; void printConnectionState(ConnectionState state) { switch (state) { case ConnectionState::Disconnected: Serial.println("Disconnected"); break; case ConnectionState::Connecting: Serial.println("Connecting..."); break; case ConnectionState::Connected: Serial.println("Connected"); break; case ConnectionState::Error: Serial.println("Connection error"); break; } } void setup() { Serial.begin(115200); printConnectionState(ConnectionState::Connecting); printConnectionState(ConnectionState::Connected); } void loop() { }
This approach makes connection states explicit and avoids using arbitrary numbers to represent network status.
15. Combining Structures and Enumerations
Structures and enums are particularly useful together.
A structure can store device information, while an enum represents the device's current state.
Example: IoT Device Status
enum class DeviceState { Offline, Starting, Running, Error }; struct IoTDevice { int deviceId; DeviceState state; float temperature; }; void displayDevice(const IoTDevice &device) { Serial.print("Device ID: "); Serial.println(device.deviceId); Serial.print("Temperature: "); Serial.println(device.temperature); Serial.print("State: "); switch (device.state) { case DeviceState::Offline: Serial.println("Offline"); break; case DeviceState::Starting: Serial.println("Starting"); break; case DeviceState::Running: Serial.println("Running"); break; case DeviceState::Error: Serial.println("Error"); break; } } void setup() { Serial.begin(115200); IoTDevice device = { 101, DeviceState::Running, 27.5 }; displayDevice(device); } void loop() { }
Why This Is Useful
The structure groups related device data into one object, and the enum makes the state meaningful.
This design is useful for smart home devices, environmental monitoring, industrial controllers, and connected sensor systems.
16. Structures for Sensor Readings
A common IoT use case is collecting several readings into a single structure.
Example: ESP32 Analog Sensor
struct SensorReading { int rawValue; float percentage; }; const int SENSOR_PIN = 34; SensorReading readSensor(int pin) { SensorReading reading; reading.rawValue = analogRead(pin); reading.percentage = (reading.rawValue * 100.0f) / 4095.0f; return reading; } void setup() { Serial.begin(115200); pinMode(SENSOR_PIN, INPUT); } void loop() { SensorReading reading = readSensor(SENSOR_PIN); Serial.print("Raw reading: "); Serial.println(reading.rawValue); Serial.print("Approximate percentage: "); Serial.print(reading.percentage); Serial.println("%"); delay(1000); }
How It Works
SensorReadingdefines two related values.readSensor()reads the analog input.- The function calculates an approximate percentage.
- The function returns both values as one structure.
loop()displays the returned information.
The percentage calculation assumes a 0–4095 scale. Actual ADC behavior depends on the ESP32 model, attenuation, configuration, and sensor. Calibrate the conversion before using it for accurate measurements.
17. Memory Considerations for Structures
A structure's size is not always equal to the sum of the sizes of its members. The compiler may add padding to satisfy alignment requirements.
Example
struct Example { char letter; int number; bool active; };
You can inspect the size with sizeof:
Serial.println(sizeof(Example));
The exact size depends on the compiler, target architecture, member types, and alignment rules.
Why Structure Size Matters on ESP32
- Large arrays of structures consume more RAM.
- Buffers should be sized according to actual requirements.
- Passing large structures by value can create unnecessary copies.
- Passing a
constreference can avoid copying when only reading. - Memory layout should not be assumed to be a portable network or file format.
If you need to transmit a structure over Wi-Fi or save it to flash, define an explicit serialization format instead of blindly sending or saving its raw memory bytes. Padding, byte order, and representation can differ between systems and software versions.
18. Using an Enum to Control an ESP32 Device
Enums can represent operating modes that determine what a device does.
Example: LED Operating Modes
enum class LightMode { Off, On, Blink }; const int LED_PIN = 2; LightMode mode = LightMode::Blink; void updateLight() { switch (mode) { case LightMode::Off: digitalWrite(LED_PIN, LOW); break; case LightMode::On: digitalWrite(LED_PIN, HIGH); break; case LightMode::Blink: digitalWrite(LED_PIN, !digitalRead(LED_PIN)); break; } } void setup() { pinMode(LED_PIN, OUTPUT); } void loop() { updateLight(); if (mode == LightMode::Blink) { delay(500); } else { delay(50); } }
This example demonstrates mode selection. In blink mode, the LED changes state every 500 milliseconds.
For projects that must remain responsive to buttons, network requests, or sensor updates, replace the blocking delays with a millis()-based timer.
GPIO 2 is an example pin; check the pinout of your development board.
19. Best Practices
For Structures
- Group related data into one structure.
- Use meaningful structure and member names.
- Initialize members before reading them.
- Pass large structures by reference when appropriate.
- Use
constreferences when a function only needs to read the structure. - Check structure sizes when working with constrained memory.
- Do not assume raw structure bytes form a portable network format.
For Enumerations
- Prefer
enum classin new C++ code when its scoped behavior is useful. - Use names that clearly describe each state.
- Use
switchto handle distinct states. - Include suitable handling for unexpected values where appropriate.
- Define explicit numeric values only when required by a protocol or external interface.
- Do not rely on an enum's default numeric values for persistent storage unless they are deliberately specified.
20. Common Mistakes
Mistake 1: Forgetting to Define the Structure
Incorrect:
SensorData sensor;
If SensorData has not been declared, the compiler cannot create a variable of that type.
Correct:
struct SensorData { float temperature; }; SensorData sensor;
Mistake 2: Using the Wrong Member Name
Structure member names must match their declarations.
struct SensorData { float temperature; }; SensorData sensor = {25.0}; Serial.println(sensor.temperature);
Mistake 3: Confusing . and ->
Use the dot operator with a structure object:
sensor.temperature
Use the arrow operator with a pointer to a structure:
sensorPointer->temperature
Mistake 4: Forgetting the Enum Scope
For a scoped enum, use the enum's name:
DeviceState::Running
Not simply:
Running
Mistake 5: Assuming an Enum Is a String
An enum stores an enumerated value, not its displayed text. Use a switch statement or a deliberate mapping function to display labels such as "Running".
Mistake 6: Assuming Structures Have No Padding
The compiler may add padding between structure members. Use sizeof to inspect the actual size on your target.
21. Practice Exercises
Beginner
- Create a
Studentstructure withid,age, andmarksmembers. - Create a
SensorDatastructure with temperature and humidity values. - Create an enum named
TrafficLightwithRed,Yellow, andGreen. - Use a
switchstatement to display the selected traffic-light state.
Intermediate
- Create an array of three sensor structures and print their readings.
- Write a function that accepts a structure by constant reference.
- Create an
enum classfor Wi-Fi states:Disconnected,Connecting, andConnected. - Combine a structure and enum to represent an IoT device's ID, sensor reading, and state.
Advanced
- Create an ESP32 program that stores multiple analog readings in a structure.
- Use an enum to switch between manual and automatic LED modes.
- Compare the memory sizes of two structures with different member orders using
sizeof. - Explain why raw structure bytes should not automatically be used as a portable communication format.
- Design a device-status structure suitable for a larger IoT monitoring application.
Summary
Structures and enumerations help you write organized, readable, and maintainable ESP32 programs.
In this lesson, you learned:
- How to declare and initialize structures.
- How to access members with
.and->. - How to pass structures to functions.
- How to create arrays and nested structures.
- How to declare and use
enumandenum class. - How to combine structures and enums to represent device information and states.
- How to use structures for sensor readings.
- How memory alignment and structure size affect embedded programs.
- How to avoid common mistakes when working with structures and enums.
Key takeaway: Use structures to group related data and enumerations to represent meaningful choices. Together, they make ESP32 programs easier to build, understand, and extend.