Function to control print/printLN

Hi

I am using an Arduino Zero.

I want to enable and disable debug output based on if the USB port is connected:

if (Serial) works great to detect connection.

I am struggling with how to enable and disable the debug.

i am thinking something like:

void debug(text){

if (Serial){

Serial.println(text);

}

The issue is that text can be different types. How do i make sure text can take different types INT,String etc. Like println can ?

Thanks

Will this work for you:

#define DEBUG
// a bunch of code...

void setup() {

#ifdef DEBUG
   Serial.begin(9600);
#endif

// more code...
}

void loop()
{
    int val;

 // some code...

#ifdef DEBUG
   Serial.print("val = ");
   Serial.println(val);
#endif

// more code..

If you have the #define for DEBUG active, the Serial object is compiled into the code. If you comment out that line, all #ifdef's become false and the Serial object is not compiled into the code. This makes it easy to leave debug code in the file, but only activate it when needed.

Or, put the #define DEBUG inside the if(Serial){}

Please read How to use the forum and use code tags next time.

An idea:

template< typename T, typename U > void debug( T data, U modifier ){
  if(Serial){
    Serial.print(data, modifier);
  }
}
template< typename T > void debug( T data ){
  if(Serial){
    Serial.print(data);
  }
}

ardy_guy:
Or, put the #define DEBUG inside the if(Serial){}

Why that way? That leaves the if statement block in the code even if you don't need it.