Programming: Macros

While programming a microcontroller, there are many situations where we need to work with constant numbers to configure a peripheral or communicate with it. Consider a simple example where you want to turn on a LED by writing the value 1 to it.

LED = 1;

In this case, we need to remember that 1 signifies turning the LED on. With the sheer amount of numbers that can go into programming the microcontroller, it is easy to lose the context, even with comments. What if we could substitute the number for a word instead?

LED = ON;

This is easier to read and understand. Conventionally, ON would have to be a variable or constant of some sort. However, that makes the program more complicated, not less complicated. What we wish is simply rename 1 with ON for this specific example. There is a mechanism in C programming to achieve this goal using macros.

A macro is a preprocessor-defined name for a piece of code. A macro is declared using #define. Unlike constants, macros do not have a memory address. Instead of being initialized at runtime (like constants would), macros are defined by preprocessors. This means that they are translated before the code even compiles. When the preprocessor runs, it essentially substitutes every instance of the macro for its definition. So, for example, this code: 

#define MY_MACRO 0


if (myVar == MY_MACRO) {

    doSomething();

    funcWithParameter(MY_MACRO);

    int x = 0xFF | MY_MACRO;

}

Is the same as this:

if (myVar == 0) {

    doSomething();

    funcWithParameter(0);

    int x = 0xFF | 0;

}

In this example, the two programs are equivalent. The former is what the programmer wrote, while the latter is what the compiler will see after the preprocessor is executed. Using macros is purely for ease of readability and clarity of what the program is doing; they don’t otherwise have any functional advantages.

(Learn more: https://www.geeksforgeeks.org/interesting-facts-preprocessors-c/

To learn more about macros, enum, and typedef import the following project into CCS:

https://github.com/VT-Introduction-to-Embedded-systems/macro_enum_typedef