This is what I use for some of my more advanced libraries. It uses macros and preprocessor directives, so it adds no runtime overhead when debugging is disabled.
By using a syntax similar to the C++ ostream
functions, it works on the Arduino, as well as on my normal computer. This means that I can use exactly the same code for development, debugging and testing on my computer, as the actual code for the Arduino.
It uses templates to overload the <<
operator.
This file is included in all of my source files. Just comment out the second line to disable debugging.
Debug.h
---
|
``` #ifndef DEBUG
|
#define DEBUG_OUT Serial // Comment out this line to disable debugging
|
#ifdef DEBUG_OUT
#pragma message "Debugging enabled"
#ifndef ARDUINO
#undef DEBUG_OUT
#define DEBUG_OUT std::cout
#endif
#endif
#ifdef DEBUG_OUT
#define DEBUGcolor=#000000[/color] do { [/color]
DEBUG_OUT << x; [/color]
} while color=#000000
#else
#define DEBUGcolor=#000000
#endif
#endif
```
|
This file is included in all files that use <<
to write to an output stream:
StreamPrinter.h
---
|
``` #ifndef StreamPrinter_h
|
#define StreamPrinter_h
|
#ifdef ARDUINO
#include <Arduino.h>
typedef Print &manipulator(Print &);
Print &endl(Print &printer) {
printer.printlncolor=#000000[/color];
printer.flushcolor=#000000[/color];
return printer;
}
template <class T> inline Print &operator<<(Print &printer, const T printable) {
printer.printcolor=#000000[/color];
return printer;
}
template <> inline Print &operator<<(Print &printer, manipulator pf) {
return pfcolor=#000000[/color];
}
#else // #ifndef ARDUINO
#include <iostream>
using std::endl;
#endif
#endif // StreamPrinter_h
```
|
This would be my main Arduino file:
debug.ino
---
|
``` #include "Debug.h"
|
#include "StreamPrinter.h"
|
void setupcolor=#000000[/color] {
Serial.begincolor=#000000[/color];
while color=#000000[/color];
}
void loopcolor=#000000[/color] {
DEBUG("Hello, World!" << endl);
DEBUG("This is a test" << ' ' << 1 << 2 << 3 << endl);
delaycolor=#000000[/color];
}
```
|
This is a file that can be compiled using desktop g++, for example unit tests for your library:
debug.cpp
---
|
``` // g++ -Wall -std=c++11 -o debug debug.cpp
|
#ifndef ARDUINO
#include "Debug.h"
#include "StreamPrinter.h"
int maincolor=#000000[/color] {
DEBUG("Hello, World!" << endl);
DEBUG("This is a test" << ' ' << 1 << 2 << 3 << endl);
return 0;
}
#endif
```
|
Pieter