Object-Oriented Programming in ESP32
Object-Oriented Programming (OOP) is a programming approach that organizes code around objects and classes rather than only functions and separate variables.
In ESP32 projects, OOP helps you organize sensors, motors, displays, relays, and communication modules into reusable components. Instead of writing all the code in one large file, you can create separate classes for different hardware devices and give each class its own data and behavior.
In this lesson, you will learn the fundamentals of OOP in C++, from classes and objects to constructors, encapsulation, inheritance, polymorphism, and practical ESP32 applications.
1. What Is Object-Oriented Programming?
Object-Oriented Programming is a programming paradigm based on objects.
An object combines:
- Data: Information stored in variables.
- Behavior: Actions implemented using functions, called methods when they belong to a class.
For example, an LED has data such as its GPIO pin and current state. Its behavior includes turning on, turning off, and changing its state.
Without OOP, you might write separate functions:
const int LED_PIN = 2; void turnOnLED() { digitalWrite(LED_PIN, HIGH); } void turnOffLED() { digitalWrite(LED_PIN, LOW); }
This approach works well for small programs. As your project grows, however, you may want to manage multiple LEDs, sensors, and other devices independently.
OOP lets you group related data and functions together.
2. What Is a Class?
A class is a blueprint for creating objects.
It defines the data and functions that objects of that class can have.
For example, a LED class could define:
- A GPIO pin.
- A method to initialize the pin.
- A method to turn the LED on.
- A method to turn the LED off.
- A method to toggle the LED.
Basic Class Syntax
class ClassName { public: // Public data and methods private: // Private data and methods };
Important points:
classdeclares a new class.publicexposes members that code outside the class can access.privaterestricts access to members from outside the class.- The semicolon after the closing brace is required.
3. What Is an Object?
An object is an instance of a class.
If a class is a blueprint for an LED controller, an object is one specific controller created from that blueprint.
For example:
class LED { public: void turnOn() { Serial.println("LED is ON"); } void turnOff() { Serial.println("LED is OFF"); } }; LED statusLED; void setup() { Serial.begin(115200); statusLED.turnOn(); statusLED.turnOff(); } void loop() { }
Output
LED is ON LED is OFF
Here:
LEDis the class.statusLEDis an object.turnOn()andturnOff()are member functions.- The dot operator (
.) accesses an object's public members.
This example prints messages only; it does not control a physical LED.
4. Creating an ESP32 LED Class
Let's create a class that controls a real LED connected to an ESP32.
Complete Code
#include <Arduino.h> class LED { private: int pin; public: LED(int gpioPin) { pin = gpioPin; } void begin() { pinMode(pin, OUTPUT); turnOff(); } void turnOn() { digitalWrite(pin, HIGH); } void turnOff() { digitalWrite(pin, LOW); } void toggle() { digitalWrite(pin, !digitalRead(pin)); } }; LED onboardLED(2); void setup() { Serial.begin(115200); onboardLED.begin(); Serial.println("LED controller initialized"); } void loop() { onboardLED.turnOn(); Serial.println("LED ON"); delay(1000); onboardLED.turnOff(); Serial.println("LED OFF"); delay(1000); }
How It Works
- The
LEDclass defines how an LED is controlled. - The private variable
pinstores the selected GPIO. - The constructor receives the GPIO number when the object is created.
- The
begin()method configures the pin as an output. turnOn()andturnOff()control the output.- The object
onboardLEDuses GPIO 2.
Hardware note: GPIO 2 is an example and may be connected to an onboard LED on some boards, but not all. Verify your board's pinout. If using an external LED, connect it with an appropriate current-limiting resistor.
The delay() calls block the main loop. For larger projects, a non-blocking implementation using millis() is often preferable.
5. Constructors
A constructor is a special member function that runs when an object is created.
It is commonly used to initialize the object's data.
A constructor has the same name as its class and does not have a return type.
Example
class Sensor { private: int pin; public: Sensor(int sensorPin) : pin(sensorPin) { } void printPin() { Serial.print("Sensor pin: "); Serial.println(pin); } }; Sensor temperatureSensor(34); void setup() { Serial.begin(115200); temperatureSensor.printPin(); } void loop() { }
Output
Sensor pin: 34
The expression : pin(sensorPin) is called a member initializer list. It initializes the member directly and is generally preferred over assigning to the member inside the constructor body.
Default Constructor
A default constructor can be called without arguments.
class Device { public: Device() { Serial.println("Device object created"); } };
You can create an object like this:
Device device;
If you define a constructor that requires arguments, C++ does not automatically generate the same kind of no-argument constructor. Define one explicitly if your design needs it.
6. Encapsulation
Encapsulation means combining data and related methods in one class while controlling access to the object's internal state.
It helps prevent other parts of a program from changing important values incorrectly.
Consider an LED controller. Its GPIO number should not normally be changed directly by unrelated code.
Example
class LED { private: int pin; public: LED(int gpioPin) : pin(gpioPin) { } void begin() { pinMode(pin, OUTPUT); } void turnOn() { digitalWrite(pin, HIGH); } void turnOff() { digitalWrite(pin, LOW); } };
The pin variable is private, so this is not allowed:
// LED led(2); // led.pin = 5; // Compilation error: pin is private
Instead, external code interacts with the class through its public methods.
Benefits of Encapsulation
- Protects internal state.
- Reduces accidental misuse.
- Makes code easier to maintain.
- Allows internal implementation changes without changing the public interface.
7. Access Specifiers
C++ provides three main access specifiers.
| Access specifier | Meaning |
|---|---|
public | Accessible from code that has access to the object |
private | Accessible only to the class's permitted members and friends |
protected | Accessible to the class, its permitted friends, and derived classes |
For example:
class Device { public: int deviceID; protected: int internalStatus; private: int secretValue; };
In general, keep implementation details private and expose only the operations that other code needs.
A class uses private access by default, while a struct uses public access by default.
8. Getters and Setters
A getter reads a private value. A setter updates a private value while allowing you to validate the new value.
Example: Sensor Threshold
class TemperatureMonitor { private: float threshold; public: TemperatureMonitor(float initialThreshold) : threshold(initialThreshold) { } float getThreshold() const { return threshold; } void setThreshold(float newThreshold) { if (newThreshold >= -40.0f && newThreshold <= 125.0f) { threshold = newThreshold; } } }; TemperatureMonitor monitor(30.0f); void setup() { Serial.begin(115200); Serial.println(monitor.getThreshold()); monitor.setThreshold(35.0f); Serial.println(monitor.getThreshold()); } void loop() { }
Output
30.00 35.00
The valid range is an example for a particular temperature-monitoring application, not a universal limit for all sensors.
The const after getThreshold() means the method promises not to modify the object's ordinary member state.
9. The this Pointer
Inside a non-static member function, this points to the object on which the function is operating.
It can be useful when a parameter has the same name as a member variable.
class Device { private: int id; public: Device(int id) { this->id = id; } void showID() const { Serial.print("Device ID: "); Serial.println(this->id); } }; Device device(101); void setup() { Serial.begin(115200); device.showID(); } void loop() { }
In this->id = id, the left side refers to the object's member, while the right side refers to the constructor parameter.
The initializer-list alternative is:
Device(int id) : id(id) { }
This is usually the cleaner choice for straightforward member initialization.
10. Abstraction
Abstraction means exposing essential operations while hiding unnecessary implementation details.
For example, when you call:
onboardLED.turnOn();
you do not need to know the internal steps required to configure the GPIO or set its output level.
The public method provides a simple interface.
In an IoT application, abstraction helps you interact with hardware without repeating low-level details throughout your main program.
A well-designed abstraction should make the device easier to use without hiding important configuration or error conditions.
11. Inheritance
Inheritance allows one class to derive from another class and reuse or extend its functionality.
The existing class is called the base class. The class that inherits from it is called the derived class.
Example
class Device { public: void start() { Serial.println("Device started"); } }; class SmartDevice : public Device { public: void connect() { Serial.println("Connecting to network"); } }; SmartDevice device; void setup() { Serial.begin(115200); device.start(); device.connect(); } void loop() { }
Output
Device started Connecting to network
SmartDevice inherits the public start() method from Device and adds its own connect() method.
Inheritance Syntax
class DerivedClass : public BaseClass { // Additional members };
Public inheritance is commonly used when a derived class represents a specialized form of its base class.
Inheritance is useful when there is a genuine relationship between the types. Do not use it merely to avoid writing a few lines of code.
12. Function Overriding and Polymorphism
Polymorphism allows different objects to respond to the same interface in different ways.
In C++, runtime polymorphism is commonly implemented using virtual functions.
Example: Different Device Behaviors
class Device { public: virtual void report() { Serial.println("Generic device"); } virtual ~Device() = default; }; class TemperatureSensor : public Device { public: void report() override { Serial.println("Reporting temperature"); } }; class MotionSensor : public Device { public: void report() override { Serial.println("Reporting motion"); } }; TemperatureSensor temperatureSensor; MotionSensor motionSensor; void setup() { Serial.begin(115200); Device* devices[] = { &temperatureSensor, &motionSensor }; for (Device* device : devices) { device->report(); } } void loop() { }
Output
Reporting temperature Reporting motion
Important Concepts
virtualenables dynamic dispatch for the method.overrideconfirms that a derived class overrides a compatible virtual method.- A base-class pointer can refer to a derived-class object.
- The method called depends on the actual object type at runtime.
- A virtual destructor is important when objects may be deleted through a base-class pointer.
This example uses statically allocated objects and does not allocate memory dynamically.
On memory-constrained microcontrollers, use polymorphism when it improves the design, but consider its memory and code-size costs.
13. Composition: Building Objects from Other Objects
Composition means a class contains objects of other classes.
It is often a natural way to organize embedded systems.
For example, a smart room monitor might contain a temperature sensor and a display controller.
class TemperatureSensor { public: float readTemperature() { // Replace with an actual sensor reading. return 26.5f; } }; class RoomMonitor { private: TemperatureSensor sensor; public: void report() { float temperature = sensor.readTemperature(); Serial.print("Temperature: "); Serial.print(temperature, 1); Serial.println(" C"); } }; RoomMonitor roomMonitor; void setup() { Serial.begin(115200); roomMonitor.report(); } void loop() { }
Output
Temperature: 26.5 C
The temperature value is simulated. An actual sensor implementation would communicate with the sensor and handle reading errors.
The RoomMonitor object contains a TemperatureSensor object. This is composition.
Composition is often simpler than inheritance when one object uses another object to perform a task.
14. Static Members
A static data member belongs to the class rather than to each individual object.
It can be useful for tracking a value shared across all objects of a class.
class Device { public: inline static int deviceCount = 0; Device() { deviceCount++; } }; Device device1; Device device2; Device device3; void setup() { Serial.begin(115200); Serial.print("Devices created: "); Serial.println(Device::deviceCount); } void loop() { }
Output
Devices created: 3
This example uses an inline static data member, supported by modern C++ toolchains. The Arduino-ESP32 toolchain normally supports this feature.
For projects using older C++ standards, declare the static member in the class and define it once in a corresponding .cpp file.
Static variables persist for the lifetime of the program. Use them only when shared class-level state is appropriate.
15. Const Member Functions
A const member function promises not to modify the object's ordinary non-mutable data members.
Example:
class Sensor { private: float temperature; public: Sensor(float initialTemperature) : temperature(initialTemperature) { } float getTemperature() const { return temperature; } };
The getTemperature() method reads the temperature without changing it.
Mark read-only methods const whenever appropriate. This makes the interface clearer and allows them to be called on const objects.
16. Practical ESP32 Project: Object-Oriented LED Controller
Let's build a reusable controller for two LEDs.
This example demonstrates:
- Classes and objects.
- Private member variables.
- Constructors.
- Public methods.
- Multiple objects created from one class.
- A non-blocking blinking pattern using
millis().
Complete Code
#include <Arduino.h> class LED { private: uint8_t pin; bool state; unsigned long previousMillis; unsigned long interval; public: LED(uint8_t gpioPin, unsigned long blinkInterval) : pin(gpioPin), state(false), previousMillis(0), interval(blinkInterval) { } void begin() { pinMode(pin, OUTPUT); digitalWrite(pin, LOW); } void update() { unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; state = !state; digitalWrite(pin, state ? HIGH : LOW); } } void turnOn() { state = true; digitalWrite(pin, HIGH); } void turnOff() { state = false; digitalWrite(pin, LOW); } bool isOn() const { return state; } }; LED led1(2, 500); LED led2(4, 1000); void setup() { Serial.begin(115200); led1.begin(); led2.begin(); Serial.println("Object-oriented LED controller started"); } void loop() { led1.update(); led2.update(); }
How It Works
- The
LEDclass defines the behavior shared by all LED objects. - Each object stores its own pin, state, and timing information.
led1toggles approximately every 500 milliseconds.led2toggles approximately every 1000 milliseconds.update()checks elapsed time without usingdelay().- Both LEDs can be updated repeatedly without deliberately blocking the main loop.
The timing is approximate because the ESP32 may perform other tasks between loop iterations.
GPIO 2 and GPIO 4 are example pins. Check your specific board's pinout and avoid pins reserved for flash, boot configuration, or other onboard hardware. Connect external LEDs through current-limiting resistors.
17. Separating an OOP Class into Header and Source Files
For a larger project, place the class declaration in a header and its method implementations in a source file.
Project Structure
ESP32OOP/ ├── ESP32OOP.ino ├── LED.h └── LED.cpp
File 1: LED.h
#ifndef LED_H #define LED_H #include <Arduino.h> class LED { private: uint8_t pin; bool state; public: explicit LED(uint8_t gpioPin); void begin(); void turnOn(); void turnOff(); bool isOn() const; }; #endif
File 2: LED.cpp
#include "LED.h" LED::LED(uint8_t gpioPin) : pin(gpioPin), state(false) { } void LED::begin() { pinMode(pin, OUTPUT); turnOff(); } void LED::turnOn() { state = true; digitalWrite(pin, HIGH); } void LED::turnOff() { state = false; digitalWrite(pin, LOW); } bool LED::isOn() const { return state; }
File 3: ESP32OOP.ino
#include <Arduino.h> #include "LED.h" LED statusLED(2); void setup() { Serial.begin(115200); statusLED.begin(); statusLED.turnOn(); Serial.println(statusLED.isOn() ? "LED ON" : "LED OFF"); } void loop() { }
Understanding LED::
The LED:: syntax specifies that a function belongs to the LED class.
For example:
void LED::turnOn() { state = true; digitalWrite(pin, HIGH); }
This is the out-of-class definition of the turnOn() member function declared in LED.h.
Important: Keep the header and source files in the expected project directory, and make sure your build system compiles LED.cpp.
18. OOP Best Practices for ESP32 Projects
When designing object-oriented embedded software:
- Keep data private unless external access is necessary.
- Expose a small, clear public interface.
- Use constructors to initialize objects consistently.
- Prefer composition when one component uses another component.
- Use inheritance when there is a genuine shared interface or type relationship.
- Use
constfor methods that do not modify object state. - Prefer fixed-size data structures where appropriate.
- Avoid unnecessary dynamic memory allocation.
- Avoid creating large numbers of temporary
Stringobjects in memory-sensitive applications. - Use non-blocking timing for responsive sensor and control loops.
- Separate hardware access from application logic where practical.
- Handle initialization failures and sensor communication errors.
- Keep hardware-specific GPIO assignments configurable.
- Test each class before integrating it into a larger IoT project.
OOP does not automatically make a program better. Small projects may work perfectly well with straightforward functions. Use classes when they make the code easier to understand, reuse, and maintain.
19. Common Mistakes
Mistake 1: Forgetting the Semicolon After a Class
Incorrect:
class Device { public: void start() { } }
Correct:
class Device { public: void start() { } };
Mistake 2: Accessing Private Members Directly
Incorrect:
// device.pin = 4;
If pin is private, access it through an appropriate public method instead.
Mistake 3: Forgetting Object Initialization
A class may require constructor arguments.
For example:
LED led(2);
If the constructor requires a GPIO number, declaring LED led; without a matching default constructor causes a compilation error.
Mistake 4: Confusing Class Names and Object Names
LED statusLED(2);
LED is the type. statusLED is the object.
Mistake 5: Incorrect Method Definition
When implementing a method outside the class, use the correct class name and signature.
void LED::turnOn() { // Implementation }
Mistake 6: Using Inheritance Without a Need
Do not create complicated inheritance hierarchies when a simple class or composition would be clearer.
Mistake 7: Blocking the Main Loop
Repeated long delay() calls can prevent your application from checking sensors, handling network events, or updating other devices promptly. Use millis()-based timing or suitable asynchronous mechanisms when responsiveness matters.
20. Practice Exercises
Beginner
- Create a
LEDclass withturnOn()andturnOff()methods. - Create two objects from the same class using different GPIO pins.
- Create a
Buzzerclass withbegin(),start(), andstop()methods. - Create a
Deviceclass with a private ID and public getter. - Write a constructor that initializes a device's pin and operating mode.
Intermediate
- Create a
Sensorclass that returns a raw ADC reading. - Add a threshold setter that rejects invalid values.
- Create a
Relayclass that encapsulates relay control. - Move a class declaration and its implementation into separate
.hand.cppfiles. - Build a non-blocking LED blinking class using
millis().
Advanced
- Create a base class for a generic sensor and derive temperature and motion sensor classes.
- Override a virtual reporting method in each derived sensor class.
- Create a room-monitor class containing sensor and display objects using composition.
- Design a class for an ESP32-based smart lighting controller.
- Explain the difference between encapsulation, abstraction, inheritance, and polymorphism.
- Compare an OOP design with a function-based design for the same IoT project.
Summary
Object-Oriented Programming helps you structure larger ESP32 applications into manageable and reusable components.
You learned about:
- Classes and objects.
- Constructors and member initializer lists.
- Encapsulation and access specifiers.
- Getters, setters, and the
thispointer. - Abstraction.
- Inheritance and method overriding.
- Runtime polymorphism using virtual functions.
- Composition and static members.
- Const member functions.
- Practical LED control using classes.
- Separating class declarations into header files and implementations into source files.
- OOP best practices for resource-constrained microcontrollers.
Key takeaway: In ESP32 programming, use classes to represent devices or logical components, keep their internal state protected, and provide clear methods for interacting with them. This makes complex IoT projects easier to extend, debug, and maintain.