Sub topic 12
Turning debug output on and off with macros
This chapter assumes you can write a sketch with setup() and loop(), and that you already use Serial.print and Serial.println for debug output. You should also know the F() macro from the earlier chapter. Here you will wrap your debug prints in preprocessor macros, so you can switch them all on or off with one line and leave no trace of them in the final program.
Why debug prints need a switch
Debug prints are useful while you build a sketch. Once the sketch works, they cause problems:
- Each
Serial.printcall adds code to the program, so the sketch gets larger. - Each string you print uses flash memory (and RAM, unless you use
F()). - Printing takes time. At 9600 baud, each character needs about one millisecond to send, so a 20-character message can hold up
loop()for around 20 ms once the transmit buffer is full. - If the board runs without a computer attached, the output is wasted.
You could delete every debug line before the final upload. Then a later bug sends you back to re-type them. A better approach is to keep the prints in the source and let the compiler decide whether to include them.
The preprocessor in one minute
Before the compiler translates your sketch, a step called the preprocessor edits the text. Lines that start with # are instructions to it. Three matter here:
#define NAME valuereplaces every later use ofNAMEwithvalue.#define NAME(x) textdefines a macro that takes an argument, and the preprocessor pastes the argument intotext.#if,#else, and#endifkeep or drop whole blocks of text depending on a condition.
The preprocessor works on text only. It does not know about types, variables, or scope. This makes macros powerful for removing code, and it is also the source of the gotchas later in this chapter.
A basic debug macro
This sketch defines DEBUG_PRINT and DEBUG_PRINTLN. When DEBUG is 1, they become calls to Serial.print and Serial.println. When DEBUG is 0, they become nothing.
#define DEBUG 1
#if DEBUG
#define DEBUG_PRINT(x) Serial.print(x)
#define DEBUG_PRINTLN(x) Serial.println(x)
#else
#define DEBUG_PRINT(x)
#define DEBUG_PRINTLN(x)
#endif
void setup() {
Serial.begin(9600);
DEBUG_PRINTLN(F("Debug output enabled"));
}
void loop() {
}With DEBUG set to 1, the preprocessor turns the line in setup() into Serial.println(F("Debug output enabled"));. With DEBUG set to 0, that line becomes an empty statement ;. The compiler never sees a Serial.println call, so the text and the call add nothing to the compiled sketch.
Notice that Serial.begin(9600) is outside the macros. In this version it always runs. You can also guard it, which is covered below.
Using the macros in a real sketch
The macros are most useful when they mark the points you want to trace. This example reads a sensor and prints debug messages that disappear when DEBUG is 0.
#define DEBUG 1
#if DEBUG
#define DEBUG_PRINT(x) Serial.print(x)
#define DEBUG_PRINTLN(x) Serial.println(x)
#else
#define DEBUG_PRINT(x)
#define DEBUG_PRINTLN(x)
#endif
const int SENSOR_PIN = A0;
const int LED_PIN = 13;
const int THRESHOLD = 512;
void setup() {
Serial.begin(9600);
pinMode(LED_PIN, OUTPUT);
DEBUG_PRINTLN(F("Setup complete"));
}
void loop() {
int raw = analogRead(SENSOR_PIN);
DEBUG_PRINT(F("raw="));
DEBUG_PRINTLN(raw);
if (raw > THRESHOLD) {
digitalWrite(LED_PIN, HIGH);
DEBUG_PRINTLN(F("LED on"));
} else {
digitalWrite(LED_PIN, LOW);
DEBUG_PRINTLN(F("LED off"));
}
delay(500);
}Change the first line to #define DEBUG 0 and upload again. The sketch behaves the same, but it prints nothing and is smaller. You can compare the "Sketch uses ... bytes" line in the IDE output panel for both settings to see the saving.
Guarding more than prints
Anything that exists only for debugging can sit inside an #if DEBUG block. That includes Serial.begin, extra variables, and helper functions.
#define DEBUG 1
#if DEBUG
#define DEBUG_BEGIN(baud) Serial.begin(baud)
#define DEBUG_PRINT(x) Serial.print(x)
#define DEBUG_PRINTLN(x) Serial.println(x)
#else
#define DEBUG_BEGIN(baud)
#define DEBUG_PRINT(x)
#define DEBUG_PRINTLN(x)
#endif
int loopCount = 0;
void setup() {
DEBUG_BEGIN(9600);
DEBUG_PRINTLN(F("Started"));
}
void loop() {
loopCount++;
DEBUG_PRINT(F("Loop number "));
DEBUG_PRINTLN(loopCount);
delay(1000);
}With DEBUG at 0, the serial hardware is never started, so the board does not spend RAM on the serial buffers and the pins used for serial stay free for other uses. If your sketch also uses serial for a real purpose, such as talking to a GPS module, keep Serial.begin unguarded.
Gotchas
An empty macro leaves a bare semicolon
When DEBUG is 0, DEBUG_PRINTLN(x); becomes ;. That is a valid empty statement, so most uses compile fine. A problem appears in an if without braces followed by else:
#define DEBUG 0
#define DEBUG_PRINTLN(x)
void setup() {
int value = 3;
if (value > 2)
DEBUG_PRINTLN(F("big"));
else
value = 0;
}
void loop() {
}This compiles, because the if body is the empty statement. The risk is different: if you ever write a macro with several statements and no braces, only the first one belongs to the if. Always use braces around if bodies that contain macro calls.
Side effects in arguments disappear
When the macro is empty, the argument is thrown away without being evaluated. This code changes behavior between the two settings:
#define DEBUG 0
#define DEBUG_PRINTLN(x)
int counter = 0;
void setup() {
Serial.begin(9600);
DEBUG_PRINTLN(counter++); // counter only increases when DEBUG is 1
Serial.println(counter); // prints 0 here, but 1 with DEBUG set to 1
}
void loop() {
}A debug statement must never change program state. Pass in a plain value, and do the work on a separate line that is always compiled.
Commas inside arguments
The preprocessor splits macro arguments at commas. DEBUG_PRINTLN(value, HEX) passes two arguments to a macro that takes one, and the build fails with an error about too many arguments. Use a variadic macro to forward everything:
#define DEBUG 1
#if DEBUG
#define DEBUG_PRINT(...) Serial.print(__VA_ARGS__)
#define DEBUG_PRINTLN(...) Serial.println(__VA_ARGS__)
#else
#define DEBUG_PRINT(...)
#define DEBUG_PRINTLN(...)
#endif
void setup() {
Serial.begin(9600);
DEBUG_PRINTLN(42, HEX); // prints 2A
DEBUG_PRINTLN(3.14159, 2); // prints 3.14
}
void loop() {
}The ... collects all arguments, and __VA_ARGS__ pastes them back in. This version also supports the number-format arguments from the formatting chapter.
Forgetting to include the macros everywhere
Macros are defined from the point of the #define to the end of the file. If you split your sketch into several tabs, a #define DEBUG in one tab is not always visible in the others, because the IDE joins the main tab and the others in a fixed order. Put the debug macros in a header file such as debug.h and include it from every file that uses them with #include "debug.h".
Choosing between macros and a variable
A plain bool debugEnabled variable also works, but it behaves differently:
| Approach | Code and text kept in the final sketch | Can change while running | Cost when off |
|---|---|---|---|
| `#define DEBUG 0` macros | No | No, needs a new upload | None |
| `bool debugEnabled` checked at run time | Yes | Yes, for example from a serial command | Flash and RAM for every print, plus a test each time |
Use macros when you want the smallest and fastest final sketch. Use a variable when you want to turn debug output on in a deployed device, for instance when a serial command sets the flag. You can also combine them: wrap the whole run-time facility in #if DEBUG.
You can also set the value from the build system instead of editing the sketch, by writing #ifndef DEBUG before the #define, so a value passed with a compiler flag takes priority:
#ifndef DEBUG
#define DEBUG 1
#endif
void setup() {
Serial.begin(9600);
#if DEBUG
Serial.println(F("Debug build"));
#endif
}
void loop() {
}Here #if DEBUG appears directly in the code. This form is useful for larger blocks, such as several lines of variable dumps that you want removed together.
Checklist
- Define
DEBUGonce, near the top of the sketch or in a shared header. - Define print macros for both settings, with empty bodies when off.
- Use
__VA_ARGS__so number formats work. - Keep side effects out of macro arguments.
- Use
F()for text inside the macros. - Upload and test with
DEBUGset to 0 before release.
Exercise
A sketch contains the line DEBUG_PRINTLN(readings[i++]);. With DEBUG set to 1 the sketch works, but with DEBUG set to 0 it reads the wrong array elements. What is wrong, and how do you fix it?
Show answer
When DEBUG is 0 the macro expands to nothing, so the argument readings[i++] is never evaluated and i is never incremented. The increment is a side effect hidden inside a debug statement. Move it to its own always-compiled line, for example i++;, and print a plain value such as DEBUG_PRINTLN(readings[i]);, so the program state is the same in both builds.
Exercise
You write #define DEBUG_PRINTLN(x) Serial.println(x) and then call DEBUG_PRINTLN(255, HEX);. The build fails. Why, and what change to the macro makes the call work?
Show answer
The preprocessor treats the comma as a separator between macro arguments, so the macro receives two arguments but is defined for one. Define it with a variadic parameter: #define DEBUG_PRINTLN(...) Serial.println(__VA_ARGS__). The call then expands to Serial.println(255, HEX); and prints FF.