如何为Arduino代码提供条件编译?

shr*_*uti 3 arduino arduino-c++

我正在开发基于 Arduino 的代码,其中我需要为串行命令提供条件编译以在串行终端上打印数据。

我在代码开头使用“#define DEBUG”,如果定义了它,则将执行所有串行打印命令,并且串行监视器上将有数据,否则,它将跳过代码中的串行打印命令。

现在,我需要开发一个代码,以便用户可以输入是否在代码中包含“#define DEBUG”语句,以选择DEBUG模式/非DEBUG模式在串行终端上打印数据。意思是需要为条件编译语句提供条件。

下面是我的代码

 #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);
     }
    }
Run Code Online (Sandbox Code Playgroud)

目前,当我不需要在终端上打印串行命令时,我正在手动注释“#define DEBUG”语句。

请建议。

感谢和问候...

Ken*_*uda 5

GvS 的答案效果很好。但是,如果要在多个位置打印,则使用大量 if 语句可能会降低可读性。您可能想要定义这样的宏函数。

#define DEBUG_ON 1
#define DEBUG_OFF 0
byte debugMode = DEBUG_OFF;

#define DBG(...) debugMode == DEBUG_ON ? Serial.println(__VA_ARGS__) : NULL
Run Code Online (Sandbox Code Playgroud)

这样,您就可以直接调用DBG()而无需 if 语句。debugMode仅当设置为时才打印DEBUG_ON

void loop() 
{
  DBG("Generate Signal ");

  for (int j = 0; j <= 200; j++)
  {
    DBG(j);
  }
  DBG("blah blah");
}
Run Code Online (Sandbox Code Playgroud)