Debugging with serial print
About this lesson
A microcontroller has no screen, so when your firmware misbehaves you cannot see why. Serial print fixes that: the chip sends text over its UART, through the board's USB chip, to the Serial Monitor on your computer. Follow one Serial.println() on an Arduino Uno R3 from a number to characters, from characters to 10-bit frames on the TX pin, and onto your screen. Then use two prints to find a real bug: a voltage that reads 0.00 at almost every knob position because of whole-number division. The Hardware lesson “Serial buses: UART, I2C and SPI” explains the wires in depth; here we use them to debug. Whole-number division itself is C++ material, covered in the C++ lesson “Variables and types”.
A bug you cannot see
Our sketch should light the LED when the knob gives more than 2.0 volts. We turn it past half way, and nothing. The code compiles and runs, but the chip has no screen. We cannot see its variables.
board Arduino Uno R3 (ATmega328P)
want knob voltage > 2.0 V -> LED on pin 13 on
got LED stays off unless the knob is turned all the way
problem the values live inside the chip, out of sight
// Arduino Uno R3: a knob (potentiometer) on A0, an LED on pin 13
void setup() {
pinMode(13, OUTPUT);
Serial.begin(9600);
}
void loop() {
int raw = analogRead(A0);
float v = raw / 1023 * 5.0; // the bug
Serial.println(raw);
Serial.println(v);
digitalWrite(13, v > 2.0);
delay(500);
}Read the lesson step by step
A bug you cannot see
Our sketch should light the LED when the knob gives more than 2.0 volts. We turn it past half way, and nothing. The code compiles and runs, but the chip has no screen. We cannot see its variables.
board Arduino Uno R3 (ATmega328P) want knob voltage > 2.0 V -> LED on pin 13 on got LED stays off unless the knob is turned all the way problem the values live inside the chip, out of sight // Arduino Uno R3: a knob (potentiometer) on A0, an LED on pin 13 void setup() { pinMode(13, OUTPUT); Serial.begin(9600); } void loop() { int raw = analogRead(A0); float v = raw / 1023 * 5.0; // the bug Serial.println(raw); Serial.println(v); digitalWrite(13, v > 2.0); delay(500); }Open a serial port
Serial.begin(9600) switches on the chip's UART, a part that sends bytes one bit at a time. 9600 is the baud rate: bits per second. They leave on pin 1 (TX), and the USB chip passes them to the Serial Monitor on your computer.
line 1 Serial.begin(9600); runs once, in setup() UART universal asynchronous receiver-transmitter baud 9600 bits per second pins 0 = RX (in), 1 = TX (out) path ATmega328P -> ATmega16U2 -> USB cable -> computerRead the knob: 512
With the knob near half way, A0 sees about 2.50 volts. analogRead turns 0 to 5 volts into a whole number from 0 to 1023, so raw becomes 512. Is that right? Let us print it.
line 2 int raw = analogRead(A0); knob about 2.50 V on A0 ADC 0..5 V -> 0..1023 (10 bits) raw 512Number to characters
Serial.println(raw) does not send the number 512 itself. It writes the characters '5', '1', '2', then CR and LF to end the line: 5 bytes. They wait in a 64-byte transmit buffer, and println returns at once.
line 4 Serial.println(raw); 5 0x35 (53) 1 0x31 (49) 2 0x32 (50) CR 0x0D (13) LF 0x0A (10) 5 bytes into the 64-byte transmit buffer CR = carriage return, LF = line feed: "start a new line"Each byte becomes 10 bits
The UART sends each byte as a frame: a start bit (0), the 8 data bits lowest first, and a stop bit (1). '5' is 0x35. At 9600 baud each bit lasts 104 µs, so one byte takes about 1.04 ms.
byte '5' = 0x35 = 00110101 frame 0 1 0 1 0 1 1 0 0 1 S 0 1 2 3 4 5 6 7 E S = start, 0..7 = d0..d7 (lowest bit first), E = end (stop bit) bit 1 / 9600 s = 104.2 µs byte 10 bits = 1.04 ms (960 bytes per second)The monitor shows 512
The USB chip hands the bytes to your computer, and the Serial Monitor shows them as text: 512. It must be set to 9600 baud too, or the bits are cut up wrongly and you see garbage. 512 looks right.
received 0x35 0x31 0x32 0x0D 0x0A shown 512 (CR LF starts the next line) monitor set to 9600 baud, the same as Serial.begin() verdict raw = 512 is what a half-turned knob should giveBut v prints 0.00
Next, Serial.println(v) prints 0.00 at every knob position except the very end. That is wrong: it should be about 2.50. raw was right and v is wrong, so the bug sits on the line between them: line 3.
line 5 Serial.println(v); shown 0.00 (floats print with 2 decimals) expected 512 * 5 / 1023 = 2.50 raw OK, v wrong -> look at line 3Whole-number division
raw / 1023 divides two whole numbers, so C++ does whole-number division and throws the fraction away: 512 / 1023 is 0, not 0.5. Then 0 × 5.0 is 0. Every raw below 1023 gives 0.
line 3 float v = raw / 1023 * 5.0; step 1 raw / 1023 = 512 / 1023 -> 0 (int / int, fraction dropped) step 2 0 * 5.0 = 0.0 so v = 0.0 for raw 0..1022, and 5.0 only at 1023 LED 0 > 2.0 is false: off unless the knob is turned all the wayFixed: v prints 2.50
Multiply first: raw * 5.0 is a float, so the division keeps its fraction. 512 × 5.0 / 1023 = 2.50. Upload again: the monitor shows 2.50, and 2.50 > 2.0, so the LED lights.
line 3 float v = raw * 5.0 / 1023; step 1 512 * 5.0 = 2560.0 (a float) step 2 2560.0 / 1023 = 2.5024 shown 2.50 LED 2.50 > 2.0 -> pin 13 HIGH, LED onPrinting takes time
Each loop sends 11 bytes: about 11.5 ms at 9600 baud. println returns at once while the 64-byte buffer has room; when it fills, println waits. Print less, use 115200 baud, and remove prints when done.
per loop 5 + 6 = 11 bytes = 110 bits 9600 11.5 ms on the wire 115200 0.95 ms on the wire buffer 64 bytes: println returns at once while there is room full println waits until bytes have gone out figure shows only the 5 bytes of raw; v adds 6 more
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01Your sketch calls Serial.begin(9600), but the Serial Monitor is set to 115200 baud. What do you most likely see?
Both ends must agree on the baud rate. At the wrong rate the monitor samples the bits at the wrong moments and turns them into the wrong bytes. Pick 9600 in the monitor to match Serial.begin(9600).
02How many bytes does Serial.println(512) send?
It sends the characters '5', '1' and '2', then a carriage return (CR, 13) and a line feed (LF, 10): 5 bytes. It sends text, not the number's binary value.
03With the default 8N1 format at 9600 baud, about how long does one byte take on the wire?
Each byte is 10 bits (start, 8 data, stop). 10 ÷ 9600 s ≈ 1.04 ms, so 960 bytes a second at most.
04On an Uno, raw = 512. What does float v = raw / 1023 * 5.0; store in v?
raw / 1023 divides two ints, so the fraction is thrown away: 512 / 1023 is 0. Then 0 × 5.0 is 0.0. Writing raw * 5.0 / 1023 makes the maths floating point and gives about 2.50.
05Your loop prints a lot and starts running slowly. What is the best explanation?
print returns at once while the transmit buffer has room. When it is full, print blocks until space frees up, so your loop runs at the speed of the serial line. Print less, use a faster rate such as 115200, and remove debug prints when you are done. At 9600 baud our 11 bytes per loop take about 11.5 ms.
Glossary
- Serial print
- Sending text from the microcontroller to your computer with Serial.print() or Serial.println(), to see values while the firmware runs.
- UART
- Universal asynchronous receiver-transmitter: the part of the chip that sends and receives bytes one bit at a time on the TX and RX pins.
- Baud rate
- The number of bits sent per second, such as 9600. Both ends of the line must use the same rate.
- Frame (8N1)
- One byte on the wire: a start bit (0), 8 data bits sent lowest first, no parity bit, and one stop bit (1). 10 bits in all.
- Transmit buffer
- A small queue in SRAM (64 bytes on the Uno) where printed bytes wait until the UART sends them.
- Serial Monitor
- The window in the Arduino IDE that shows the text the board sends over USB.
- CR and LF
- Carriage return (ASCII 13) and line feed (ASCII 10): the two characters println adds to end a line.
- Integer division
- Dividing one whole number by another in C++: the result is a whole number and the fraction is thrown away, so 512 / 1023 is 0.
Notes and sources
- The card shows the lines that matter. Line 1 runs once in setup(), next to pinMode(13, OUTPUT); lines 2 to 6 are the body of loop(), which ends with delay(500). The full sketch is in the step notes.
- Serial.begin(9600) uses the default format, SERIAL_8N1: 8 data bits, no parity bit, 1 stop bit, so every byte costs 10 bits on the wire. When nothing is being sent the TX line rests at 1, and the start bit's drop to 0 tells the receiver a byte is coming.
- The 64-byte transmit buffer size comes from the Arduino AVR core (HardwareSerial.h) for chips with at least 1 KB of SRAM, like the ATmega328P. Bytes leave from the front of the buffer, oldest first. A simplification: on AVR, if the buffer is empty and the UART's data register (UDR0) is free, the first byte skips the buffer and goes straight to the register.
- On the Uno R3, pins 0 and 1 are wired to the USB chip. Connecting other things to them can disturb printing and even uploads.
- In C++, dividing an int by an int gives an int, with the fraction dropped. As soon as one side is a float (5.0), the maths is done in floating point. raw / 1023.0 * 5 would also work.
- Arduino language reference: Serial (pins, Serial Monitor)
- Arduino language reference: Serial.begin()
- Arduino language reference: Serial.print()
- Arduino language reference: Serial.println()
- Arduino language reference: Serial.write() (transmit buffer, blocking)
- Arduino AVR core: HardwareSerial.h (buffer sizes)
- Arduino language reference: analogRead()
- Arduino language reference: division operator
- cppreference: Arithmetic operators (integer division)
- J. W. Valvano, Embedded Systems: Shape the World, ch. 11: Serial interfacing (UART frames)
- Arduino UNO R3 product datasheet (A000066)
Quiz Unlocks after the last step.