Search code examples
arduinoarduino-c++

How to provide conditional compilation to Arduino code?


I am working on Arduino based code in which I need to provide conditional compilation for serial commands to print data on serial terminal.

I am using "#define DEBUG" at the start of code, if it is defined then all the serial print commands will be executed and will have data on serial monitor otherwise, it will skip the serial print commands in the code.

Now, I need to develop a code such that user can provide input whether to include "#define DEBUG" statement in the code or not, to choose DEBUG mode/non DEBUG mode to print data on serial terminal. Meaning need to provide condition to conditional compilation statement.

Below is my code

 #define DEBUG         // Comment this line when DEBUG mode is not needed

    void setup()
    {
      Serial.begin(115200);
    }

    void loop() 
    {
      #ifdef DEBUG
      Serial.print("Generate Signal ");
      #endif 

     for (int j = 0; j <= 200; j++)
     {
      digitalWrite(13, HIGH);
      delayMicroseconds(100); 
      digitalWrite(13, LOW);
      delayMicroseconds(200 - 100);
     }
    }

Currently I am manually commenting "#define DEBUG" statement when I don't need to print serial command on terminal.

please suggest.

Thanks & Regards...


Solution

  • GvS's answer works fine. However, if you want to print at many locations, having a lot of if statements may reduce readability. You may want to define a macro function like this.

    #define DEBUG_ON 1
    #define DEBUG_OFF 0
    byte debugMode = DEBUG_OFF;
    
    #define DBG(...) debugMode == DEBUG_ON ? Serial.println(__VA_ARGS__) : NULL
    

    This way, you can just call DBG() without if statements. It prints only when debugMode is set to DEBUG_ON.

    void loop() 
    {
      DBG("Generate Signal ");
    
      for (int j = 0; j <= 200; j++)
      {
        DBG(j);
      }
      DBG("blah blah");
    }