Sub topic 7
Tracing your sketch with debug prints
This chapter shows how to use Serial.print and Serial.println to follow what a sketch is doing and to find the line where it goes wrong. It assumes you can already do the following:
- Write and upload a sketch with
setup()andloop(). - Start serial with
Serial.begin(9600)and open the Serial Monitor at a matching baud rate. - Use
printandprintlnfor text and numbers. - Use the
F()macro. - Read a pin with
analogReadand write one withdigitalWrite.
Why print debugging fits a microcontroller
A typical Arduino has no debugger you can step through. Boards like the Uno have no hardware debug interface, and the IDE setup for one is complex on boards that do. The Serial Monitor is the lowest-effort way to see inside a running sketch. You add a line that prints a value, upload, and compare what you see with what you expected.
Debug printing answers two kinds of questions:
- Did this code run? You print a marker at a checkpoint. If the marker never appears, execution never reached that line.
- What was the value? You print a variable. If the value differs from your expectation, the bug is at or before that line.
Each pass narrows the search. A fixed routine keeps you from guessing.
What to print
Pick prints that test a specific hypothesis. Printing everything produces noise you then have to read.
| Print this | It answers |
|---|---|
| A fixed marker such as `[setup] done` | Did execution reach this point? Did the board reset? |
| The inputs to a function when it starts | Was the function called, and with what? |
| A result just before it is used | Is the value what the next line assumes? |
| The old and new state at a transition | Did the state change when and how it should? |
| A branch label inside each `if` or `else` | Which branch ran? |
| `millis()` with each message | How long between events? In what order? |
Give every message a label. A bare 512 tells you little when three different values scroll past. Printing [loop] sum=512 tells you which variable it is and where it came from. A short tag in square brackets makes the output easy to scan and easy to find with the monitor's text, and it makes the prints easy to find in the source when you remove them.
Worked example: a wrong average
The sketch below should average 100 analog readings. The author expects values between 0 and 1023, but the output looks wrong.
const int SENSOR_PIN = A0;
const int SAMPLES = 100;
void setup() {
Serial.begin(9600);
Serial.println(F("[setup] done"));
}
void loop() {
int sum = 0;
for (int i = 0; i < SAMPLES; i++) {
sum += analogRead(SENSOR_PIN);
}
Serial.print(F("[loop] sum="));
Serial.println(sum);
int average = sum / SAMPLES;
Serial.print(F("[loop] average="));
Serial.println(average);
delay(1000);
}On an Uno or Nano, an int is 16 bits and holds at most 32767. With a pin reading around 500, the true sum is about 50000. The monitor shows something like this:
[setup] done
[loop] sum=-15536
[loop] average=-155The first print is the clue. A sum of 100 readings that are each 0 to 1023 cannot be negative, so the fault is at or before the accumulation, not in the division. The average line only repeats the damage. Checking the type of sum finds it: the value wrapped past 32767 into the negative range. This is called integer overflow.
Fix it with a wider type:
const int SENSOR_PIN = A0;
const int SAMPLES = 100;
void setup() {
Serial.begin(9600);
Serial.print(F("[setup] sizeof(int)="));
Serial.println(sizeof(int));
}
void loop() {
unsigned long sum = 0;
for (int i = 0; i < SAMPLES; i++) {
sum += analogRead(SENSOR_PIN);
}
Serial.print(F("[loop] sum="));
Serial.println(sum);
unsigned long average = sum / SAMPLES;
Serial.print(F("[loop] average="));
Serial.println(average);
delay(1000);
}The sizeof(int) print in setup() is a cheap way to confirm what your board does. It prints 2 on AVR boards such as the Uno and 4 on 32-bit boards such as the ESP32 or Uno R4. The original bug would not appear on a 32-bit board, which is why code that works on one board can fail on another.
A small tracing helper
Repeating three or four print calls for every value gets tedious. A helper function keeps the format consistent and adds a timestamp.
void trace(const __FlashStringHelper *label, long value) {
Serial.print(millis());
Serial.print(F(" ms | "));
Serial.print(label);
Serial.print(F(" = "));
Serial.println(value);
}
int counter = 0;
void setup() {
Serial.begin(9600);
Serial.println(F("[setup] done"));
}
void loop() {
counter++;
trace(F("counter"), counter);
if (counter % 3 == 0) {
trace(F("multiple of three"), counter);
}
delay(500);
}The F() macro produces a __FlashStringHelper*, so the parameter type must match. Serial.print has an overload for that type, which is why label prints correctly. A plain const char* parameter would not accept an F() string. The timestamp column lets you see the spacing of events and tell whether two messages happened close together or a second apart.
Tracing state transitions
For code with modes, such as idle, running, and error, print only when the state changes. Printing the state on every pass of loop() buries the one useful line in thousands of repeats.
enum State { IDLE, RUNNING, FAULT };
State state = IDLE;
State lastState = FAULT; // differs from state, so the first pass prints
void setup() {
Serial.begin(9600);
}
void loop() {
int reading = analogRead(A0);
if (reading > 800) {
state = FAULT;
} else if (reading > 300) {
state = RUNNING;
} else {
state = IDLE;
}
if (state != lastState) {
Serial.print(F("[state] "));
Serial.print(lastState);
Serial.print(F(" -> "));
Serial.print(state);
Serial.print(F(" at reading="));
Serial.println(reading);
lastState = state;
}
}The lastState variable remembers the previous value, so a line appears only when something changed. Enum values print as their integer numbers (0, 1, 2). That is enough for a quick trace, and you can translate them with a switch if you want names.
Gotchas
Printing is not free, and it can change the behavior you are watching.
- Prints take time. At 9600 baud, each character takes about one millisecond to send. A 30-character line costs roughly 30 ms once the transmit buffer is full. A bug that depends on tight timing can disappear when you add prints, and appear again when you remove them.
- Do not print inside an interrupt service routine. Serial output relies on interrupts itself, and a slow print inside an ISR can stall the sketch. Instead, set a flag or store a value in a
volatilevariable inside the ISR and print it fromloop(). - Setup messages can be missed on some boards. An Uno resets when the Serial Monitor opens, so you see
setup()output. Boards with native USB, such as the Leonardo and Micro, do not reset, and early prints can be lost before the monitor connects. Awhile (!Serial) { }line afterSerial.beginmakes those boards wait for the monitor. Do not use it on a board that must run without a computer attached, because it will wait forever. - A print can hide a type problem.
Serial.printlnon acharprints a letter, while the same value in anintprints a number. If a printed value looks odd, check its declared type. - Output volume. A print on every pass of
loop()can run thousands of times per second and floods the monitor. Later chapters cover limiting the rate withmillis(), switching prints off with macros, and what happens when the serial buffer fills.
A working routine
- Reproduce the problem and write down what you expected and what you saw.
- Print a marker at the start of
setup()andloop()to confirm the board runs your sketch. - Print the inputs and outputs of the function you suspect, each with a label.
- Compare the values with what you calculated by hand for one case.
- Move the prints toward the first point where the value is wrong, and repeat.
- After the fix, remove the prints or wrap them in a macro so you can turn them off.
Exercise
A sketch sums 50 analog readings into an int and prints [loop] sum=-8192 on an Uno, although each reading is at most 1023. What does the negative sum tell you, which line do you fix, and why would the same sketch print correct values on an ESP32?
Show answer
The sum of 50 readings of up to 1023 is at most 51150, which is above 32767, the largest value of a 16-bit int on the Uno. The value wrapped around into the negative range (integer overflow). Fix the declaration of sum by changing it to unsigned long (or long), and keep the average in a type that can hold the result. On an ESP32 an int is 32 bits, so the same sum fits and no overflow occurs.
Exercise
You add Serial.println(state) to the first line of loop() and the monitor scrolls too fast to read. Which change shows only the useful information, and what extra variable does it need?
Show answer
Print only when the state changes. Keep a lastState variable, compare state != lastState, print the old and new values inside that if, and then assign lastState = state.