Creating a class in Arduino (C++) involves writing a header file (.hpp or .h) and a source file (.cpp). This is standard C++ practice and allows for better organization and reusability of code in Arduino projects.
Letβs write a simple class called LedController that turns an LED on/off and blinks it.
LedController.hpp#ifndef LEDCONTROLLER_HPP
#define LEDCONTROLLER_HPP
#include <Arduino.h>
class LedController {
public:
LedController(uint8_t pin); // Constructor
void begin(); // Set pinMode
void on(); // Turn LED on
void off(); // Turn LED off
void blink(int delayMs); // Blink LED
private:
uint8_t _pin;
};
#endif // LEDCONTROLLER_HPP
LedController.cpp#include "LedController.hpp"
LedController::LedController(uint8_t pin) {
_pin = pin;
}
void LedController::begin() {
pinMode(_pin, OUTPUT);
}
void LedController::on() {
digitalWrite(_pin, HIGH);
}
void LedController::off() {
digitalWrite(_pin, LOW);
}
void LedController::blink(int delayMs) {
on();
delay(delayMs);
off();
delay(delayMs);
}
main.ino (Arduino sketch)#include "LedController.hpp"
LedController led(LED_BUILTIN); // Use built-in LED
void setup() {
led.begin();
}
void loop() {
led.blink(500);
}
LedController.hpp and LedController.cpp in the same folder as your .ino file.Would you like a more advanced example, like a sensor driver or communication protocol class?