Try Embedded

"C++ on a microcontroller: classes, RAII and templates"

A Pin class, an interrupt lock that frees itself, and a ring buffer template checked at compile time, with no heap, no exceptions and no virtual calls, on an…

Firmware · Intermediate

In a real product: Driver layer of a smart thermostat (Smart home): Firmware teams write drivers in a small subset of C++ that costs no more than C.

C++ on a microcontroller doesn't mean new, exceptions and the standard library. Used well, it gives the same machine code as careful C, while the compiler checks more. This sketch shows the three features embedded teams use most, on an Uno: a class that owns a pin, an RAII guard that turns interrupts off and always back on, and a template ring buffer whose size is checked when the program is compiled.

A timer interrupt pushes the button's state into the buffer 100 times a second, and the main loop takes it out and drives the LED with it.

What you'll learn

  • A class with a constructor, const methods and private data, and why it costs nothing beyond its one byte
  • RAII: a lock whose destructor restores the interrupt flag, even on an early return
  • A class template Ring<T, N> with static_assert that refuses a size that isn't a power of two
  • constexpr, references, and the rules: no heap, no exceptions, no RTTI, no virtual calls in an interrupt

How it works

Pin holds a pin number. The constructor sets the mode, on(), off() and read() are inline, and read() is const because it changes nothing. sizeof(Pin) is 1: a class costs only its data.

InterruptLock saves SREG (with the global interrupt flag) in its constructor and runs cli(). Its destructor writes SREG back. Any block that declares one, { InterruptLock lock; ... }, runs with interrupts off and gets them back when the block ends, whichever way it ends. That is the idea behind RAII ("Resource Acquisition Is Initialisation"): the resource is freed by a destructor, so no code path can forget it.

Ring<T, N> is the ring buffer from the unit-test project, made generic. static_assert((N & (N - 1)) == 0, ...) stops the build if N isn't a power of two, the bug that project's tests catch at run time. The compiler makes one copy of the code for each T and N used, and each one is as fast as a hand-written version.

Timer1 interrupts at 100 Hz and pushes the button's state. The main loop pops what's there, inside an InterruptLock because the buffer's indexes are shared with the interrupt. The rest of the loop runs with interrupts on.

Try this

  • Change Ring<uint8_t, 16> to Ring<uint8_t, 12> and read the compiler's message.
  • Add a toggle() method to Pin, and a Pin for a second LED.
  • Put a return inside the locked block and check, with SREG & 0x80, that interrupts come back on anyway.

sketch.ino

// C++ without the heap: a Pin class, an RAII interrupt lock and a Ring<T, N> template. A 100 Hz timer interrupt
// samples the button (pin 2) into the ring; the main loop drives the LED (pin 12) from it.
#include <avr/interrupt.h>

class Pin {
public:
  constexpr explicit Pin(uint8_t n) : number(n) {}
  void output() const { pinMode(number, OUTPUT); }
  void inputPullup() const { pinMode(number, INPUT_PULLUP); }
  void on() const { digitalWrite(number, HIGH); }
  void off() const { digitalWrite(number, LOW); }
  bool read() const { return digitalRead(number) == HIGH; }
private:
  uint8_t number;
};

// Interrupts off for as long as the object lives; the old state back when it goes.
class InterruptLock {
public:
  InterruptLock() : saved(SREG) { cli(); }
  ~InterruptLock() { SREG = saved; }
  InterruptLock(const InterruptLock &) = delete;            // can't be copied: one lock, one release
  InterruptLock &operator=(const InterruptLock &) = delete;
private:
  uint8_t saved;
};

template <typename T, uint8_t N>
class Ring {
  static_assert(N >= 2 && (N & (N - 1)) == 0, "Ring size must be a power of two");
public:
  bool put(const T &value) {
    uint8_t next = (head + 1) & (N - 1);
    if (next == tail) return false;                          // full
    data[head] = value;
    head = next;
    return true;
  }
  bool get(T &value) {
    if (head == tail) return false;                          // empty
    value = data[tail];
    tail = (tail + 1) & (N - 1);
    return true;
  }
  constexpr uint8_t capacity() const { return N - 1; }
private:
  T data[N];
  volatile uint8_t head = 0, tail = 0;
};

constexpr Pin led(12), button(2);
Ring<uint8_t, 16> samples;
volatile uint16_t dropped;

ISR(TIMER1_COMPA_vect) {
  if (!samples.put(button.read() ? 0 : 1)) dropped++;        // 1: pressed (pulled up)
}

void setup() {
  Serial.begin(9600);
  led.output();
  button.inputPullup();
  // Timer1, CTC, 16 MHz / 256 / 625 = 100 Hz.
  TCCR1A = 0;
  TCCR1B = _BV(WGM12) | _BV(CS12);
  OCR1A = 624;
  TIMSK1 = _BV(OCIE1A);
  Serial.print(F("sizeof(Pin) = "));
  Serial.print(sizeof(Pin));
  Serial.print(F(", sizeof(InterruptLock) = "));
  Serial.print(sizeof(InterruptLock));
  Serial.print(F(", ring holds "));
  Serial.println(samples.capacity());
}

void loop() {
  uint8_t pressed = 0, got = 0, s;
  {
    InterruptLock lock;                                      // the ring's indexes are shared with the ISR
    while (samples.get(s)) { pressed = s; got++; }
  }                                                          // interrupts are back on here
  if (pressed) led.on(); else led.off();

  static unsigned long last = 0;
  if (millis() - last >= 1000) {
    last = millis();
    Serial.print(F("took "));
    Serial.print(got);
    Serial.print(F(" samples, button "));
    Serial.print(pressed ? F("pressed") : F("released"));
    Serial.print(F(", dropped "));
    Serial.println(dropped);
  }
  delay(50);
}

Lessons behind it