Tag Archives: improve

C++ Templates for Embedded Code

Templates are a powerful feature of the C++ language but their syntax can be complex. This causes some developers to not use them, while others are concerned that templates might cause bloat to the compiled code.

I will explain how templates work and how you may use them in your code. Although the examples I provide are for the Arduino Uno and Adafruit Feather M0, the concepts will work with any platform and with all modern C++ compilers.

The first part explains the basics and function templates. Then I will explain template classes and template specialisation.

What are Templates

Templates were introduced to allow a single function to work with many different types or to build generic types from classes. They also enable an efficient way for the compiler to generate many variants of the same code for you.

If you are experienced with Python or JavaScript you may be familiar with dynamically typed variables. In these languages, the same function can be called with parameters of various types. Be careful not to confuse dynamically typed variables with the concept of templates.

In C++ the types of function templates and template classes are defined at compile-time and thus, they are type-safe. In Python and JavaScript, however, the dynamic types of variables are checked at runtime and are not type-safe.

Here is a simple example written for the Arduino Uno:

template<typename Value>
void circularShift(Value &value) {
    const bool firstSet = (value & 0b1u);
    value >>= 1;
    if (firstSet) {
        value |= static_cast<Value>(0b1u) << (sizeof(Value)*8-1);

uint32_t value1 = 0xabcd0123u;
uint16_t value2 = 0x4545u;

void setup() {
    while (!Serial) {}

void loop() {
    Serial.println(value1, BIN);    
    Serial.println(value2, BIN);    

In this example, the circularShift function is similar to executing >> 1 on a value, shifting all of the bits one position to the right. The difference is that circularShift “wraps” the bits, so the right-most bit (which would otherwise be shifted out of the value) moves to the left-most bit. For example:

0b11100101 >> 1  // results in 01110010
circularShift(0b11100101) // results in 11110010

To test the function, we use a 32-bit and a 16-bit value declared in lines 10 and 11 of the example code. In the loop() function the values are printed and then circular-shifted to the right in lines 21 and 22.

It is not necessary to understand the syntax of the function template for now, I will discuss this later on.

Compiling the Example

Processing our example the compiler will treat the function template differently than regular functions. It will keep the template function prototype in memory as it is but will not generate any code for it, yet.

Continue reading C++ Templates for Embedded Code

Guide to Modular Firmware

This article is for embedded software developers with good knowledge of C or C++, but struggle with large and complex projects.

If you learn developing embedded code, e.g. using the Arduino IDE, you find plenty of small example programs. It is helpful for a quick start, but as soon your project grows, help about software design is rare.

In contrast, if you learn software development for desktop applications, project structures and software design is an integral part of the learning process.

With this short article, I will give you a simple guideline, how you can build a modular structure for your firmware, which will keep your code clean and maintainable for large and complex projects.

Refactor your Code

If you start a new project, you can already prepare the structures as described. I assume in this article you already have a working firmware but need to improve the code quality.

Improving the code in an iterative process is called refactoring. Testing is an integral part of this process. After each small change, you test if the software is still working as expected.

In desktop application development, there are unit tests to ensure the integrity of smaller modules. I found it difficult to apply unit tests to embedded code, if not for small independent functions or modules. Therefore you have to use a simple run-time test of your software, to make sure it is still working as expected.

Refactoring only changes the code, but not the functionality. Even if you change names, move code around and change implementations, the function of your code stays exactly the same. It is important you either change or extend functionality or do refactoring, but never do both at the same time (or in the same commit).

Use a Version Control System

Changing your code without version history is a bad idea. If you do not already manage your code in a version control system, now it is the time to start using one.

If you never used a version control system before, use GIT and read one of the many tutorials on how to use it. There are graphical user interfaces for any operating system, so you do not have to work on the console. It does not matter how you manage your code – it is important that you use a version control system.

After each small successful change, you should commit a new version. If you run into troubles at a later stage, you can easily analyse every change you did on the code and go back to the last working version.

The Demo Setup

If you like to follow along using the real demo setup, you will need an Arduino Uno, three LEDs with matching resistors and two pushbuttons. The example code expects a circuit shown in the next illustration.

A Shockingly Bad Example to Start With

The example code to start with is something I sadly see often. Please open a second browser window with the code at the following URL:


I can not use a really complex firmware for this article, and your source code may be in a different state. Nevertheless, this example code contains most of the elements I like to discuss.

Because of the length of the code, I will just link to the full examples. The code snippets in the article should have the correct line numbers, so you can easily find the locations.

Continue reading Guide to Modular Firmware

It’s Time to Use #pragma once

In my opinion, preprocessor macros and the outdated #include mechanism are one of the worst parts of the C++ language. It is not just these things are causing a lot of problems, even more, it is very time consuming to find them.

This article will focus on #pragma once. In the past, I already wrote articles about how to avoid macros and why you should use namespaces.

While I usually focus on embedded development on this blog, this topic especially aplies to desktop software. It is valid not only for C++, but also C programs.

As usual, I try to cover the topic in detail to bridge any knowledge gaps you may have.

What is the Problem with Macro Header Guards?

Macro based header guards can lead to unexpected problems. In the following sections, I will explain the core concepts and demonstrate the problem using a simple example.

Compiling Units

In C and C++ a compile unit usually consists of a header (.h or .hpp) and implementation file (.c or .cpp). It is the lowest level of encapsulation. The header file contains the interface of the unit, while the cpp or c file contains the implementation.

Continue reading It’s Time to Use #pragma once

Write Less Code using the “auto” Keyword

The auto keyword was introduced with C++11. It reduces the amount of code you have to write, reduces repetitive code and the number of required changes. Sadly, many C++ developers are not aware of how useful this keyword is. Especially embedded code can gain a lot by its usage.

In this article, I try to explain a number of useful cases of the auto keyword, using Arduino example code. The same principles are valid for any embedded environment which is using a modern C++ compiler. The C++11 standard is eight years old, and meanwhile, every C++ compiler should support it.

The examples are written for Arduino or Adafruit SAMD boards using the Arduino IDE. The toolchain for these boards use a compiler which supports more features explained in this article. Using auto with AVR code is possible too, just give it a try.

The “auto” Keyword

The auto keyword was introduced to instruct the compiler to automatically deduce a type from the given context. In programming language terms, they call this a placeholder type specifier.

C++11 mainly introduced the auto keyword for variable declarations. These are the main focus of this article.

Simple Variable Declarations

At any point in your code, where you declare a variable which is initialized, you can use auto instead of a type.

auto variable = <some expression>
Continue reading Write Less Code using the “auto” Keyword

Class or Module for Singletons?

Should you use a class or a module with a namespace for a singleton interface in your firmware? I found there are many misunderstandings which lead beginners to make a wrong decision in this matter. With this article, I try to visualize these misunderstandings with simple example code for the Arduino platform.

Before we start, as with all of these topics, there is no simple rule, and there are a lot of exceptions. In the end, it heavily depends on the compiler and architecture you use.

The Example Use Case

I like to write simple driver code for my firmware, which flashes two LEDs for a given duration. The used PINs for the LEDs shall be configurable. In my main loop, I will flash the two LEDs at different durations.

The use case is no real-world example, but it contains all elements of configuration, initialization and usage.

Using a Simple Class

For the first test case, I write a simple class, without constructor and all required methods for the use case.

Continue reading Class or Module for Singletons?