Debug print with ifdef and a header file

Updated on 2 December 2021
dev board Arduino M0
firmware Arduino
chip SAMD21
features debug ifdef print header
This tutorial is more than 1 year old. If the steps below do not work, then please check the latest versions and the documentations of the individual tools used.

Buy the components

Code

Download code arduino-debug.ino
#define DEBUG  // Comment to turn off debug statements
#include "DebugUtils.h"

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);

  #ifdef DEBUG
  SerialUSB.begin(9600);
  while (!SerialUSB) { }
  delay(100);
  #endif

  DEBUG_PRINT("Start blinking");
}

void loop() {
  DEBUG_PRINT("HIGH");
  digitalWrite(LED_BUILTIN, HIGH);
  delay(500);

  DEBUG_PRINT("LOW");
  digitalWrite(LED_BUILTIN, LOW);
  delay(500);
}

Makefile

BOARD?=arduino:samd:mzero_bl
PORT := $(shell ls /dev/cu.usbmodem*)
BUILD=build

.PHONY: default lint all flash clean

default: lint all flash clean

lint:
	cpplint --extensions=ino --filter=-legal/copyright *.ino

all:
	arduino-cli compile --fqbn $(BOARD) --output-dir $(BUILD) ./

flash:
	arduino-cli upload --fqbn $(BOARD) --port $(PORT) --input-dir $(BUILD)

clean:
	rm -r build

Prototype

A photo of the actual setup.

Debug print with ifdef and a header file prototype

Serial console

Serial output from the firmware.

Debug print with ifdef and a header file serial console

Description

Some patterns for toggling on and off debug print messages in Arduino firmware with #ifdef and a header file DebugUtils.h.

References

Watch