Make your debugging life easier with preprocessor marcos

These tips maybe useful for you when you need to debug your code without a real debugger. Typically, you will push variables's value to some displays such as the console on Windows/ Linux or the "Serial monitor" on Arduino. And when you don't want to see those outputs anymore, you delete those "cout"/ "print" lines, or better to comment them out.

You can save yourself from manually comment/ uncomment those lines (maybe scattered all over the place) repeatedly. Simple put this at the start of your source file:

1
#define DEBUG

And wrap your debugging lines with this:

1
2
3
4
5
6
7
#ifdef DEBUG
...
Serial.print(x);
or ...
cout << x << endl;
...
#endif

From now on, you can quickly toggle debugging output by comment/ uncomment the #define line.

There's also the inverted version. For example, only output PWM to motors when not debugging:

1
2
3
#ifndef DEBUG
motor_set(pwm)
#endif

You can have as many flags as you want. 1 flag for each module, 1 flag to toggle timing function execution...

1
2
3
#define DEBUG_SPEED
#define DEBUG_POSITION
#define TIME

You can also execute "or" operation. For example, on Arduino, we need to enable Serial to push out debugging values:

1
2
3
#if defined(DEBUG) || defined(TIME)
Serial.begin(115200);
#endif

Hope these tips can help you.