C++ classes for I/O pin abstraction

Allow me to shamelessly plug my open source project https://Kvasir.io . The Kvasir::Io portion provides pin manipulation functions. You must first define your pin using a Kvasir::Io::PinLocation like so:

constexpr PinLocation<0,4> led1;    //port 0 pin 4
constexpr PinLOcation<0,8> led2;

Notice that this does not actually use RAM because these are constexpr variables.

Throughout your code you can use these pin locations in 'action factory' functions like makeOpenDrain, set, clear, makeOutput and so on. An 'action factory' does not actually execute the action, rather it returns a Kvasir::Register::Action which can be executed using Kvasir::Register::apply(). The reason for this is that apply() merges the actions passed to it when they act on one and the same register so there is an efficiency gain.

apply(makeOutput(led1),
    makeOutput(led2),
    makeOpenDrain(led1),
    makeOpenDrain(led2));

Since the creation and merging of actions is done at compile time this should yield the same assembler code as the typical hand coded equivalent:

PORT0DIR |= (1<<4) | (1<<8);
PORT0OD |= (1<<4) | (1<<8);

The Wiring project uses abstraction like that:

http://wiring.org.co/

and the compiler is written in C++. You should find plenty of examples in the source code. The Arduino software is based on Wiring.


Short answer: sadly, there is no library to do what you want. I've done it myself numerous times but always in non open-source projects. I'm considering putting something up on github but I'm not sure when I can.

Why C++?

  1. Compiler is free to use dynamic word-size expression evaluation. C propagates to int. Your byte mask/shift can be done faster/smaller.
  2. Inlining.
  3. Templatizing operations lets you vary word size and other properties, with type-safety.