how to use conditional macros in Arduino?

Hi,

I am developing a code for Arduino in which I am using "#define DEBUG" statement.

If DEBUG is defined, I need to print debug log (which I have included as Serial.print() statement.) and if DEBUG is not defined I don't need to print the data present in Serial.print() statement. I am not able to recognize how to use conditional "#define DEBUG" in my code.

One way is to use input from serial terminal, Meaning if I'll give input from serial terminal as "DEBUG", "#define DEBUG" should be included in code and if I'll send "RESET" from serial terminal, it should not include "#define DEBUG" and code will not print any data on serial terminal.

Please guide to implement such scenario.

right now I am manually commenting #define DEBUG from the code when I don't need to print data on serial terminal, need to automate it based on inputs received from serial terminal.

Below is the code:

#define DEBUG

void setup()
{
Serial.begin(115200);
delay(1000);
pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
#ifdef DEBUG
Serial.print("Hello World!!!");
#endif

digitalWrite(LED_BUILTIN, HIGH);
delay(1000);
digitalWrite(LED_BUILTIN, LOW);
delay(1000);
}
Thanks & Regards, Shruti

One way is to use input from serial terminal, Meaning if I'll give input from serial terminal as "DEBUG", "#define DEBUG" should be included in code and if I'll send "RESET" from serial terminal, it should not include "#define DEBUG" and code will not print any data on serial terminal.

You cannot do it like that. The #define statements are only read when the code is compiled so your debug statements are either compiled into the code or not. You cannot turn on a #define whilst the code is running.

What you can do is to use an ordinary variable and test its value to determine whether debugging is turned on or not and change the value of that variable whilst the program is running by reading user input.

The disadvantage of that approach is that the debug code will be compiled into the program whether or not it is used whereas using #define means that debug code is not in the code unless needed.