user
How to write a class for Arduino (hpp and cpp)?
alphonsio

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.

βœ… Step-by-Step Example

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);
}

πŸ”§ How to Use This:

  1. Place LedController.hpp and LedController.cpp in the same folder as your .ino file.
  2. Arduino IDE automatically includes them in the compilation.
  3. Use the class in your sketch just like any other object.

Would you like a more advanced example, like a sensor driver or communication protocol class?