【问题标题】:How to provide conditional compilation to Arduino code?如何为 Arduino 代码提供条件编译?
【发布时间】:2019-08-19 10:16:33
【问题描述】:

我正在编写基于 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);
     }
    }

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

请提出建议。

感谢和问候...

【问题讨论】:

    标签: arduino arduino-c++


    【解决方案1】:

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

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

    这样,您可以只调用DBG() 而不使用 if 语句。仅当 debugMode 设置为 DEBUG_ON 时才会打印。

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

    【讨论】:

      【解决方案2】:

      创建一个变量:

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

      在您对 Serial.print 的调用中加上:

      if (debugMode == DEBUG_ON) {
         Serial.print("Debugging message");
      }
      

      使用来自用户的输入,将 debugMode 切换为 DEBUG_ON/DEBUG_OFF。

      【讨论】:

        猜你喜欢
        • 2022-07-29
        • 1970-01-01
        • 2020-02-06
        • 2013-06-08
        • 1970-01-01
        • 2011-05-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多