debug version of serial.print

hello, I try to make a debug version of serial.print and serial.println so I can make someting like

#boolean DEBUG = true;

void debugprint(toprint)
{
if debug
{
Serial.print(toprint);
}
}

void debugprintln(toprint)
{
if debug
{
Serial.println(toprint);
}
}

In the program I can then use debugprint as replacement for Serial.print and the same for debugprintln.

I don’t get this working. Can someone help ?

You have lowercase and upercase for the same variable, but the compiler is case sensitive. Try this:

#boolean DEBUG = true;
void debugprint(toprint) { if DEBUG Serial.print(toprint); }
void debugprintln(toprint) { if DEBUG Serial.println(toprint); }

In the case where all my Serial output is for debugging, I use this:

#define DEBUG true  //set to true for debug output, false for no debug ouput
#define Serial if(DEBUG)Serial

Add this to setup() if you are using a Leonardo, Pro Micro, or other ATmega32U4 based board and don’t want the program to run until the Serial Monitor has been opened while debug output is enabled:

while (DEBUG && !Serial);

This can easily be extended to allow multiple levels of debug output, still with no overhead:

#define DEBUG_ERROR true
#define DEBUG_ERROR_SERIAL if(DEBUG_ERROR)Serial

#define DEBUG_WARNING true
#define DEBUG_WARNING_SERIAL if(DEBUG_WARNING)Serial

#define DEBUG_INFORMATION true
#define DEBUG_INFORMATION_SERIAL if(DEBUG_INFORMATION)Serial

void setup() {
  Serial.begin(9600);
  while (!Serial);
  DEBUG_ERROR_SERIAL.println("This is an error message");
  DEBUG_WARNING_SERIAL.println("This is a warning message");
  DEBUG_INFORMATION_SERIAL.print("The state of pin 5 is ");
  DEBUG_INFORMATION_SERIAL.println(digitalRead(5) ? "HIGH" : "LOW");
  Serial.println("This is standard program output");
}

void loop() {}

It can also be useful if you use Serial in your non-debug code and only want to turn the debug output on/off.

You can use the boolean debug macros to switch on and off other parts of your code too.

Hmm, tried something like this but it didn't work but will try it thanks.

Tried it and it works great.

Thanks a lot

void debugprint(toprint) {
   if debug {
     Serial.print(toprint);
   }
}

A problem is that you need a "type" for the toprint argument, but Serial.print() accepts a whole bunch of different types (strings, floats, integers, integers AND base, floats AND precision...) AFAIK, there's not clever way to do this in C/C++, so you're forced into using less elegant techniques like Pert's preprocessor-macro based technique.