Toggle DEBUG on Arduino


Supporting Member
« M² Supporter »
May 16, 2019
I thought I would pass along a new trick I discovered this weekend!

It's so incredibly common for those of us to add Serial.print(); to our code to send console output for testing purposes. Basically an "I got here!". Or to output a variable to see if it was what we expected it to be. This is great, but when we're done we remove the code to save space in memory and boost performance. Only to later discover a new bug and add it all back.

This little gem will fix that for you by allowing you to toggle debugging at a compiler level on the Arduino. Just add this to the top of your code.

#define DEBUG true // set true or false to enable or disable debug
#define Serial if(DEBUG)Serial // the compiler will ignore or include serial
The main reason this is so great is that it allows you to sprinkle Serial.print(); statements anywhere in your code, with no additional work or extra code like #if or #else around them. No need to make a special debug routine or anything else. It just works! Yay.
May 22, 2019
Yes, preprocessor directives are really handy for selectively removing debug code.

You can also use them for platform dependent code, so you can use the same modules for desktop and Arduino programs.

Here’s an example from David Hansel’s Altariduino code

#if defined(__AVR_ATmega2560__)
#include "host_mega.h"
#elif defined(__SAM3X8E__)
#include "host_due.h"
#elif defined(_WIN32) || defined(__linux__)
#include "host_pc.h"
#error requires Arduino Mega2560, Arduino Due or Windows/Linux PC
This actually selects one of three different header files, depending on which platform the emulator is being compiled for.


The Geek Pub
Staff member
May 15, 2019
Keller, TX
Yeah. I actually struggled with that exact problem a few months back. I removed my debug code only to add it all back when I found something was still broken. I I just left it in. Maybe I'll go back and do this next time I touch that project!