EMBEDDED SYSTEMS & MICROCONTROLLERS · PAGE 54
C++ Hardware Abstraction Layers
Same application, different chip.
An abstraction layer hides chip-specific details behind a common interface. Application code calls led.on() and does not care which register makes it happen.
Moving to a new chip then means rewriting only the driver classes. An abstract base class gives a fixed interface, though virtual calls add a small cost; templates can remove it.
Keep the interface small and honest about what the hardware cannot do.
EXAMPLE
class Pin {
public:
virtual void high() = 0;
virtual void low() = 0;
};
class LedDriver {
public:
explicit LedDriver(Pin &p) : pin(p) {}
void on() { pin.high(); }
void off() { pin.low(); }
private:
Pin &pin;
};