ConditionalDebug

One can use #define directives to conditionally enable or disable Serial.print lines in your arduino code. This approach allows you to compile the code with or without the serial debugging messages, thereby reducing the compiled code size when debugging messages are disabled.

// Define a macro to toggle serial debug messages
#define ENABLE_SERIAL_DEBUG true

#if ENABLE_SERIAL_DEBUG
#define DEBUG_PRINT(x) Serial.print(x)
#define DEBUG_PRINTLN(x) Serial.println(x)
#else
#define DEBUG_PRINT(x)
#define DEBUG_PRINTLN(x)
#endif

// Initialize WiFi
void initWiFi() {
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  DEBUG_PRINT("Connecting to WiFi network: ");
  DEBUG_PRINT(WIFI_SSID);
  unsigned long ms = millis();
  while (WiFi.status() != WL_CONNECTED) {
    DEBUG_PRINT(".");
    delay(1000);
  }
  DEBUG_PRINTLN("");
  DEBUG_PRINTLN("WiFi connected");
  DEBUG_PRINT("IP address: ");
  DEBUG_PRINTLN(WiFi.localIP());
}

Explanation:

Conditional Debugging Output: The ENABLE_SERIAL_DEBUG macro is defined at the beginning of the sketch. When set to true, it enables Serial.print and Serial.println statements throughout the code. Inside the code, DEBUG_PRINT(x) and DEBUG_PRINTLN(x) macros are used instead of Serial.print and Serial.println. These macros expand to either the respective serial print functions or to nothing (if debugging is disabled).

Reduced Compiled Size: When ENABLE_SERIAL_DEBUG is set to false, all DEBUG_PRINT and DEBUG_PRINTLN statements are effectively removed during compilation. This results in a smaller compiled binary size, as the compiler does not include unused debug statements.

Usage: To enable or disable debugging output, simply change the value of ENABLE_SERIAL_DEBUG to true or false, respectively.

Functionality: This setup allows you to easily switch between debugging modes without modifying each individual Serial.print statement in your code. It helps maintain code readability and reduces the overhead of debug statements when they are not needed.

By implementing conditional debugging with #define directives and macros, you can efficiently manage debug output in your ESP32-CAM application, ensuring optimal performance and easier debugging during development phases while minimizing compiled code size for deployment. Adjust the macro value as needed based on whether you want debugging output via the serial monitor or not.


© Prabu Anand K 2020-2026