Go Down

Topic: Toggling Debug Code (Read 15 times) previous topic - next topic

econjack

It may be that everyone here already knows this technique, but I'll risk a repeat here.

During development, we all use Serial.print() to help debug our code. When things seem stable, we go back and remove the debug code...only to find out a few days later that we need the debug code...again. My solution is to leave this "scaffolding code" in the source file, but toggle it out for the release version. To do this, add:

#define DEBUG 1

at the top of the source (sketch) file. Where you have debug code, surround it with another preprocessor directive:

#ifdef DEBUG
Serial.print("Some debug stuff follows");
// More debug code...
#endif

As long a DEBUG is define, the debug statements are compiled into the current sketch. However, changing the first line to:

//#define DEBUG 1

makes the preprocessor define for DEBUG disappear by commenting it out. Since it is no longer defined in the program, anything between the #ifdef and #endif is no longer part of the source file from the compiler's point of view. This makes it easy to add and remove debug code. On my most recent project, the code size was about 11.8K with the #define for DEBUG, and 8.2K when it was undefined (I seem to write a lot of buggy code).

I hope this might help some newbies...

Groove

#1
Apr 17, 2010, 05:17 pm Last Edit: Apr 17, 2010, 05:21 pm by GrooveFlotilla Reason: 1
You don't even need:
Code: [Select]
#define DEBUG 1 because:
Code: [Select]
#define DEBUG
will suffice with a "#ifdef"

Better yet:
Code: [Select]
#ifdef DEBUG
 #define DEBUG_PRINT(x)  Serial.println (x)
#else
 #define DEBUG_PRINT(x)
#endif


Then you can liberally scatter your code with "DEBUG_PRINT ("I think I'm here");",
all controlled by a simple "#define DEBUG"
Per Arduino ad Astra

econjack

Yep, that would work too. Question: Wouldn't this macro approach require the #ifdef-#else-#endif to surround every statement in a block of debug statements? If so, the macro approach would require more typing, right?

Groove

Quote
Wouldn't this macro approach require the #ifdef-#else-#endif to surround every statement in a block of debug statements?


No, all the if..else does is define or (more importantly) not define the DEBUG_PRINT.

The "DEBUG_PRINT("Now I'm here");" here stays in the code; if DEBUG is defined, it prints, if DEBUG isn't defined, the print simply isn't there.

Try it!   8-)
Per Arduino ad Astra

econjack

Okay...I see what you're saying now. However, suppose I have debug code like the following:

Serial.print("pressCounter = ");
Serial.print(pressCounter, DEC);

My solution looks like:

#ifdef DEBUG
Serial.print("pressCounter = ");
Serial.print(pressCounter, DEC);
#endif

What does your approach look like?

Go Up