Sub topic 4
Seeing values with the Serial Monitor
This chapter assumes you can upload a sketch from the Arduino IDE, you know setup() and loop(), and you can declare variables of the basic types. A board such as an Uno should be connected over USB. You do not need any extra parts, because the Serial Monitor works with a bare board.
Why print values
A microcontroller has no screen. When a sketch misbehaves, you cannot see which variable holds the wrong number or which branch ran. The standard fix is to send text from the board to your computer over the USB cable and read it in the IDE's Serial Monitor.
This is called serial communication: bits are sent one after another over a single wire. On an Uno, the Serial object sends and receives bytes through the same USB connection you use for uploading. It uses pins 0 (RX, receive) and 1 (TX, transmit) internally.
The loop looks like this:
Starting the connection with Serial.begin()
Call Serial.begin() once, normally at the top of setup(). Its argument is the baud rate, the number of signal changes per second. For plain serial data on an Uno, this is effectively bits per second.
void setup() {
Serial.begin(9600);
Serial.println("Sketch started");
}
void loop() {
}The Serial Monitor has its own baud rate drop-down in the bottom right corner. It must match the value in Serial.begin(). If it does not, you see garbled characters such as ÿ or ¿, or nothing readable at all. This is the most common serial mistake.
Common baud rates are 9600, 57600, and 115200. 9600 is the traditional default in tutorials. 115200 moves data about twelve times faster, which helps when you print a lot.
Opening the Serial Monitor
- Upload the sketch.
- Choose Tools > Serial Monitor, or use the magnifying glass icon at the top right of the IDE. The shortcut is Ctrl+Shift+M (Cmd+Shift+M on macOS).
- Set the baud rate drop-down to match
Serial.begin().
Opening the Serial Monitor resets most Uno-style boards. The sketch restarts from the top of setup(), so you see the start-up messages. Boards with native USB, such as the Leonardo, do not reset this way. Their Serial may not be ready for a moment after boot, so text printed right at the start of setup() can be lost. On those boards, add this line after Serial.begin():
while (!Serial) {
// Wait for the USB serial connection to open.
}Do not use that line on an Uno. It is not needed there, and on boards where Serial is a hardware UART it returns at once anyway. Be aware that on a native USB board it blocks the sketch until a monitor is open, so remove it for a standalone project.
print() and println()
Two functions do most of the work:
Serial.print(value)sends the value and stays on the same line.Serial.println(value)sends the value and then a line break, so the next output starts on a new line.
Both accept strings, characters, and numbers. Combining them lets you label values:
int sensorValue = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
sensorValue = analogRead(A0);
Serial.print("A0 = ");
Serial.println(sensorValue);
delay(500);
}With nothing wired to A0, the pin is floating and the numbers wander. That is normal. Touch the pin with a jumper wire connected to 5V or GND to see it jump to about 1023 or 0.
Text in the F() macro
String literals such as "A0 = " normally occupy both flash memory (where the program lives) and SRAM (working memory). An Uno has only 2 KB of SRAM, so many debug messages add up. Wrapping a literal in F() keeps it in flash only:
Serial.println(F("Sensor reading follows"));This works with print() and println(). It does not work for strings you build at run time.
How values are formatted
print() chooses a format from the type of its argument.
| Call | Output | Notes |
|---|---|---|
| `Serial.print(78)` | `78` | Integers print in decimal. |
| `Serial.print(1.23456)` | `1.23` | Floats show 2 decimal places by default. |
| `Serial.print(1.23456, 4)` | `1.2346` | The second argument sets decimal places for floats. |
| `Serial.print('N')` | `N` | A `char` prints as a character. |
| `Serial.print(78, BIN)` | `1001110` | Binary. |
| `Serial.print(78, HEX)` | `4E` | Hexadecimal. |
| `Serial.print(78, OCT)` | `116` | Octal. |
| `Serial.print("Hello")` | `Hello` | A string literal. |
For integer types, the second argument is the number base. For floats, it is the number of decimal places. The meaning depends on the type of the first argument.
One frequent confusion involves byte and char. A byte value of 65 prints as 65. A char holding 65 prints as A. If you want the number from a char, cast it: Serial.println((int)myChar);. If you want the character from a number, cast it to char.
Another point involves the constants HIGH and LOW. They are the numbers 1 and 0, so printing the result of digitalRead() shows 1 or 0, not words.
const byte buttonPin = 2;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
int state = digitalRead(buttonPin);
Serial.print("Button pin: ");
Serial.println(state);
delay(200);
}With INPUT_PULLUP, an unpressed button reads 1 and a pressed button, wired to GND, reads 0.
Using the monitor as a tracing tool
Printing is the main debugging technique on a small board. Three habits make it effective.
Label every value. A column of bare numbers tells you little. Print a name before each one.
Print where decisions happen. To find out which branch of an if ran, print inside each branch:
const int threshold = 512;
void setup() {
Serial.begin(9600);
}
void loop() {
int reading = analogRead(A0);
if (reading > threshold) {
Serial.print("HIGH branch, reading = ");
} else {
Serial.print("LOW branch, reading = ");
}
Serial.println(reading);
delay(500);
}Print the loop counter and key variables. Inside a for loop, print the index along with the value. This exposes off-by-one errors, where a loop runs one time too many or too few.
Tab-separated output for plotting
The IDE also has a Serial Plotter (Tools > Serial Plotter). It draws a graph of numbers sent over serial. Send each sample on one line, and separate several values with a comma or a space:
void setup() {
Serial.begin(115200);
}
void loop() {
Serial.print(analogRead(A0));
Serial.print(",");
Serial.println(analogRead(A1));
delay(20);
}The plotter works best with numbers only. Leave out text labels, or the line may not be parsed as data. In recent IDE versions, a label:value format is also accepted. The Serial Monitor and Serial Plotter cannot hold the same port at once, so close one before you open the other.
Reading input from the monitor
Serial works in both directions. The input field at the top of the Serial Monitor sends text to the board. Use Serial.available() to find out how many bytes are waiting, and Serial.read() to take one byte.
void setup() {
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
Serial.println(F("Type 1 to turn the LED on, 0 to turn it off."));
}
void loop() {
if (Serial.available() > 0) {
char c = Serial.read();
if (c == '1') {
digitalWrite(LED_BUILTIN, HIGH);
Serial.println(F("LED on"));
} else if (c == '0') {
digitalWrite(LED_BUILTIN, LOW);
Serial.println(F("LED off"));
}
}
}Next to the input field is a line-ending drop-down. If it is set to "Newline" or "Both NL & CR", every message you send also includes a hidden newline character, '\n'. This sketch ignores characters other than '1' and '0', so the extra newline is skipped. Sketches that read numbers or compare whole strings often break because of those hidden characters. If the input seems wrong, set the drop-down to "No line ending" and test again.
Serial.read() returns an int. It returns -1 when nothing is available. Always check Serial.available() first, as above.
Costs and pitfalls
Serial output is useful but not free.
- Printing takes time. Each character at 9600 baud takes about one millisecond (10 bits per character at 9600 bits per second). A 20-character line takes roughly 20 ms. Sending short lines at a higher baud rate reduces the delay.
- The transmit buffer is small. On an Uno it holds 64 bytes. When it is full,
print()waits until space is free, which stalls yourloop(). This matters in timing-sensitive code, such as themillis()examples later in this tutorial. - Pins 0 and 1 are shared. Do not wire other components to pins 0 and 1 while using
Serialon an Uno. Uploads can fail, and the output can be corrupted. - Memory. Every string literal uses SRAM unless you wrap it in
F(). A sketch with many messages can run out of memory and behave strangely without any error message. - Flooding. Printing in a fast
loop()with nodelay()scrolls too quickly to read. Add a short delay while you inspect values, or print only when something changes.
The last point has a simple remedy. Remember the previous value and print only on change:
int lastReading = -1;
void setup() {
Serial.begin(9600);
}
void loop() {
int reading = analogRead(A0);
if (reading != lastReading) {
Serial.print("A0 changed to ");
Serial.println(reading);
lastReading = reading;
}
}Troubleshooting summary
| Symptom | Likely cause | Fix |
|---|---|---|
| Garbled characters | Baud rate mismatch | Match the drop-down to `Serial.begin()`. |
| Nothing appears | Wrong port, or `Serial.begin()` missing | Check Tools > Port and the code. |
| Start-up text missing on a native USB board | `Serial` not ready yet | Wait with `while (!Serial)`. |
| Input comparisons fail | Hidden newline from the line-ending setting | Choose "No line ending" or skip `'\n'` and `'\r'`. |
| Numbers print as `65` instead of `A` | Value is `byte` or `int`, not `char` | Cast to `char`. |
| Sketch is slow or stalls | Too much output for the baud rate | Print less, or use 115200. |
Exercise
A sketch calls Serial.begin(115200), and the Serial Monitor is set to 9600. The sketch prints Serial.println("Ready"). What do you see, and what is the fix?
Show answer
You see garbled or unreadable characters, because the two sides use different baud rates and misread the timing of the bits. Set the Serial Monitor drop-down to 115200 so it matches Serial.begin(). Changing the baud rate in the sketch to 9600 would also work.
Exercise
Write a loop() body that reads analog pin A0 once per second and prints a line such as "Temperature raw: 312". Then say what changes if you want to see the value in hexadecimal.
Show answer
Code: int raw = analogRead(A0); Serial.print("Temperature raw: "); Serial.println(raw); delay(1000); To see hexadecimal, pass HEX as the second argument: Serial.println(raw, HEX); An integer of 312 then prints as 138.
Exercise
Why can a sketch that prints many messages freeze or behave oddly on an Uno even though it compiles, and what two techniques reduce the problem?
Show answer
Each string literal is copied into the 2 KB of SRAM, and the 64-byte transmit buffer fills when you print faster than the baud rate can send. Wrapping literals in F() keeps them in flash, and printing less often (or only when a value changes) keeps the buffer from filling. A higher baud rate also helps.