Template library

1 post / 0 new
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I'm working on a template library for efficient access to peripherals and other routine tasks (link here: https://github.com/technik/etl). The idea is to use C++ features like templates and constexpr to generate code that is very fast, and way more secure than the usual C approach.

Let me explain with an example. Let's say you have an LED at pin 5 of PortB, and you want to toggle it really fast. You would do this:


OutputPin<PortB, 5> led;


for(;;) {





There are a few things happening here. First, since you declared the led as an OutputPin, the code will automatically configure the port for you on construction, and will not let you change it by accident. That saves you time, and reduces the possibilites for errors.

Since in most occasions, the pin functions can not change, because the hardware is physically determined, it is good practice for the code to enforce consistency by default.

Of course, for situations where your pins really change functionality on runtime, you can just use a regular DigitalPin, and that's it.

Also, since the pin mode was automatically configured, you can not forget to do it. And if you remove the pin later, you will not accidentally leave some dead initialization code anywhere.


But the best thing is that, since all information is provided at compile time, the compiler optimizes everything away, and generates structs which occupy literally 0 bytes in memory, and the smallest possible assembly. You couldn't generate faster code in C, and it wouldn't even be this safe.

For Pin creation (and configuration):


ldi r24,lo8(32)

out 36-0x20,r24


and for setHigh (and similarly setLow):


ldi r24,lo8(32)

out 37-0x20,r24


For easy testing, I've also provided some extra headers so the library can be used in arduino, where you could do something like this, and still generate the exact same assembly:

OutputPin<Pin13> led;

digitalWrite(led, High);


That is many times faster than the equivalent arduino code, and is no harder to use at all.

The library is header-only, so it will work with all build systems. Just add it to your include path.

The project is currently just a proof of concept. I'm still figuring out the best syntax and API, and have only implemented digital pins use, but I plan on adding more functionality like peripheral access and common algorithms implemented in a similar fashion.

In the meantime, all comments and suggestions are welcome. I'd also like to know what peripherals/algorithms/whatever you would like to have implemented.