How do you debug Arduino code using the Serial Monitor?

ampheoampheo
2 min read

Debugging Arduino code using the Serial Monitor is one of the most effective and beginner-friendly ways to find and fix issues in your sketch. Here's a complete guide:


What Is the Serial Monitor?

The Serial Monitor is a window in the Arduino IDE that shows messages sent over the USB serial connection. You use it to print values, track execution, and monitor sensor or variable behavior in real-time.


Step 1: Setup Serial Communication

Add this line to your setup() function to initialize communication:

cpp

Serial.begin(9600);  // or 115200 for faster output

This sets the baud rate, which must match the Serial Monitor's setting.


Step 2: Print Debug Messages

Use Serial.print() or Serial.println() to send data or messages:

cpp

int sensorValue = analogRead(A0);
Serial.print("Sensor value: ");
Serial.println(sensorValue);

This will print something like:

yaml

Sensor value: 512

Step 3: Trace Code Execution

Insert prints in different parts of your code to see if they're reached:

cpp

Serial.println("Entering loop");

This helps find where your code freezes, restarts, or gets stuck.


Step 4: Monitor Variable Changes

Print changing variables to understand how they're behaving:

cpp

Serial.print("x = ");
Serial.println(x);

You can compare this against expected values to detect bugs in logic or math.


Step 5: Add Delays for Readability (optional)

If your data scrolls too fast, slow it down:

cpp

delay(500);  // 0.5 second between prints

Step 6: Clean Output (Optional Tricks)

  • Use Serial.print("\t") for tab-separated values (e.g., for Excel plots)

  • Use Serial.print("Value: "); Serial.println(value, 3); to print float with 3 decimals

  • Use Serial.flush(); only when absolutely needed (forces completion of outgoing data)


Bonus Tips

ProblemSerial Debugging Trick
Code not entering functionAdd a Serial.println("Inside function X");
Value not changingCheck sensor or loop logic with prints
Random resetsAdd Serial.println("Restarted") to setup()
Time-related issuesPrint millis() to understand timing

Example: Debugging a Button Input

cpp

const int buttonPin = 2;
int buttonState = 0;

void setup() {
  pinMode(buttonPin, INPUT);
  Serial.begin(9600);
  Serial.println("Setup complete");
}

void loop() {
  buttonState = digitalRead(buttonPin);
  Serial.print("Button state: ");
  Serial.println(buttonState);
  delay(200);
}
0
Subscribe to my newsletter

Read articles from ampheo directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

ampheo
ampheo