Debugging microcontrollers

It has been a little painful, but I finally managed to put together two little C preprocessor files you can include in your source code to have a nice set of debug tools: SerialDebug and LedDebug.

SerialDebug is a set of macros providing to every Arduino program an overloaded DEBUG instruction to use to print debug information on the device Serial console and you can activate or de-activate them all with a simple #define statement:

#define SERIAL_DEBUG_ENABLE true
// Optionally you can redefine the SERIAL_DEBUG_SEPARATOR
#include <SerialDebug.h>

void setup() {
  // the following statement is required only if you don't already have 
  // a Serial.begin(...) statement in your code
  SERIAL_DEBUG_SETUP(9600);
  ...
}

void loop() {
  int sensorReading = analogRead(A0);
  // DEBUG statements, including the SERIAL_DEBUG_SETUP will be completely
  // ignored if SERIAL_DEBUG_ENABLE is set to false
  DEBUG(sensorReading);
  ...
  // the DEBUG macro supports up to 9 parameters
  DEBUG(anotherSensorReading, someComputedVariable, theSystemStatusCode);
}

LedDebug, on the other end, is a set of macros you might want to adopt in case your system doesn’t provide a serial output or you just can’t connect to a serial port: it uses the built in led (or any other led attached to a digital pin, if needed) to provide some visual feedback on what’s happening within your program. Like SerialDebug, you can activate or de-activate all macros with a simple #define statement:

#define LED_DEBUG_ENABLE true
// Optionally you can redefine the LED_DEBUG_PIN, LED_DEBUG_DELAY and LED_DEBUG_LENGHT
#include <LedDebug.h>

void setup() {
  // no initialization is needed, just consider that when LED_DEBUG_ENABLE is switched on
  // every PULSE statement will turn the LED_DEBUG_PIN (pin 13 by default) into OUTPUT mode
  // which means _do not connect anything to that pin_ !
  ...
  PULSE(2); // two pulses to indicate the setup process is completed
}

void loop() {
  PULSE(); // every loop emit a single pulse
  ...
  if (analogSensorReading > 512) {
    PULSE(5,50); // emit 5 fast pulses
  } else {
    PULSE(2,500); // emit 2 slow pulses
  }
}

As you can imagine the LedDebug capabilities are quite limited so I use it only when really unable to get to a Serial connection.

By using macros only I achieved one fundamental goal: the ability to have absolutely no impact on production code because all the debug statements are going to be completely stripped out when the macro is de-activated.

If you find those files of any use I would appreciate a comment or a mention.

Have fun!