Arduino

Easily add Debug Messages in Arduino Code

I use the Arduino IDE for almost all of my microcontroller coding. It is a simple editor without a great debugger built in. This means that for most of us, we start putting in a lot of print statements just to help with debugging. All this extra code is great for debugging but is not great in production (the finished code). This is because it uses up a lot of precious memory and code space, make your code more complicated, and slows things down a bit.

The best way would be to create all those print statement so that they can be there when you are working on the code but removed when you create the final version. In comes compiler macros to solve this problem. Compiler macros allows you to create code that can be dependant or changed when the code is compiled. In this case, added or removed at compile time depending on what you want.

I alway put the following code at the top of my Arduino sketches:

#define __DEBUG__ // Comment out to turn off debuging

#ifdef __DEBUG__
#define DEBUG(s)   { Serial.print(F(s)); }
#define DEBUGVAR(s,v)  { Serial.print(F(s)); Serial.print(v); }
#define DEBUGHEX(s,v) { Serial.print(F(s)); Serial.print(F("0x")); Serial.print(v, HEX); }
#else
#define DEBUG(s)
#define DEBUGVAR(s,v)
#define DEBUGHEX(s,v)
#endif

Then in my code I can liberally add in some DEBUG lines throughout the code list this.

DEBUG("This is a debug message.\n")

With debugging turned on then the message above will be printed out on the serial console. If you comment out the #define __DEBUG__ first line, then it will not be compiled in. Work with __DEBUG__ turned on and when you are ready for production code, then comment it out.

Leave a Comment

Your email address will not be published. Required fields are marked *