Sub topic 11
Printing to the Serial Monitor
This chapter assumes you have already uploaded Blink to your board. It also assumes you can select the board and port in the IDE, and that you know what setup() and loop() do. Here you will make the board send text to your computer and read it in the Serial Monitor. This is the main way to see what a sketch is doing, since a bare board has no screen.
What serial communication is
Serial communication sends data one bit at a time over a single line. On an Uno, the USB cable carries these bits between the board and your computer. The board's Serial object is the sketch's handle to that connection.
Two details matter before you write any code:
- Both sides must agree on the speed, called the baud rate. Baud is roughly the number of bits per second. If the sender and receiver use different rates, the receiver shows garbage characters.
- The same USB link carries your uploads and your serial text. The Serial Monitor and the uploader therefore cannot use the port at the same time.
Your first serial sketch
This sketch opens the connection once in setup(), then prints one line each second.
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println("Hello, Arduino!");
delay(1000);
}Serial.begin(9600) starts the connection at 9600 baud. It belongs in setup() because it only needs to run once. Serial.println() sends the text followed by a line break, so each message appears on its own line. delay(1000) pauses for one second so the output does not scroll too fast to read.
Running it and opening the Serial Monitor
- Select your board and port, as in the earlier chapters.
- Click Upload and wait for the upload to finish.
- Open the Serial Monitor from the Tools menu, or click the magnifying-glass icon at the top right of the IDE.
- Check that the baud rate dropdown at the bottom of the Serial Monitor says 9600 baud.
You should see Hello, Arduino! appear about once per second. If you see strange symbols instead, the baud rates do not match. Change the dropdown to the value in Serial.begin().
The Serial Monitor controls
The Serial Monitor has a few controls worth knowing:
| Control | What it does |
|---|---|
| Baud rate dropdown | Sets the speed the computer uses to read the port. It must match `Serial.begin()`. |
| Line ending dropdown | Chooses what the monitor appends to text you send to the board: nothing, a newline, a carriage return, or both. |
| Autoscroll | Keeps the newest line in view. Turn it off to study older output. |
| Clear output | Empties the display without affecting the board. |
The line ending setting only affects what you type into the monitor's input box and send to the board. It does not change how the board's own output is shown.
Print and println
Serial.print() sends text without a line break. Serial.println() sends the text and then a line break. Combining them lets you build a single line from several pieces:
void setup() {
Serial.begin(9600);
}
void loop() {
int seconds = millis() / 1000;
Serial.print("Uptime (s): ");
Serial.println(seconds);
delay(1000);
}Here millis() returns the number of milliseconds since the board started. Dividing by 1000 gives whole seconds, because both values are integers. The first call prints a label and stays on the line. The second prints the number and ends the line.
Both functions accept several types. Text in double quotes is a string, and numbers print as digits. You can also give a second argument to choose a number format:
void setup() {
Serial.begin(9600);
int value = 42;
Serial.println(value); // 42
Serial.println(value, BIN); // 101010
Serial.println(value, HEX); // 2A
Serial.println(3.14159, 2); // 3.14
}
void loop() {
}For a floating-point number, the second argument is the count of decimal places. For an integer, it is the number base. Without a second argument, a float prints with two decimal places.
Debugging with serial output
Printing values is the simplest debugging tool you have. A few habits make it more useful:
- Print a label with every value, such as
"sensor=", so you can tell the lines apart. - Print once at the start of
setup()so you know the sketch started. If you never see it, the problem is in the upload or the baud rate, not in your logic. - Print inside branches of an
ifstatement to learn which path ran.
const int buttonPin = 2;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP);
Serial.println("Setup complete");
}
void loop() {
if (digitalRead(buttonPin) == LOW) {
Serial.println("Button pressed");
} else {
Serial.println("Button released");
}
delay(500);
}With INPUT_PULLUP, the pin reads HIGH when nothing is connected and LOW when a button wired to ground is pressed. Even without a button attached, the sketch prints "Button released", which confirms that the code runs.
Sending data from the computer to the board
The connection works in both directions. Type text in the Serial Monitor's input box and press Enter to send it. The sketch reads it with Serial.available() and Serial.read():
void setup() {
Serial.begin(9600);
Serial.println("Type a character and press Enter.");
}
void loop() {
if (Serial.available() > 0) {
char c = Serial.read();
if (c != '\n' && c != '\r') {
Serial.print("You sent: ");
Serial.println(c);
}
}
}Serial.available() returns how many bytes are waiting in the receive buffer. Serial.read() removes one byte and returns it. The check for '\n' and '\r' skips the line ending characters that the monitor adds, depending on the line ending setting. Without it, you would see extra empty "You sent:" lines.
Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| Garbled characters | Baud rate mismatch | Set the dropdown to the value in `Serial.begin()`. |
| Nothing appears | Missing `Serial.begin()`, wrong port, or the monitor opened on a different port | Check the selected port and the sketch. |
| Upload fails while the monitor is open | The monitor is holding the port | Close the monitor or let the IDE release the port, then upload again. |
| Output scrolls too fast | No `delay()` in `loop()` | Add a delay, or print only when something changes. |
| Missing first lines | The board restarted when the monitor opened | Wait briefly in `setup()`, or press the reset button. |
Printing too much
Serial printing is slow compared with the rest of your code. At 9600 baud, the board sends about 960 characters per second. If loop() prints long messages with no delay, the code spends most of its time waiting for the transmit buffer to drain. That can slow down timing-sensitive tasks. Raise the baud rate, print less, or print only when a value changes.
Summary of the workflow
- Call
Serial.begin(rate)once insetup(). - Use
Serial.print()andSerial.println()to send text and values. - Upload the sketch, then open the Serial Monitor.
- Match the monitor's baud rate to the one in your sketch.
- Remove or reduce the printing once the sketch works.
Exercise
Your sketch calls Serial.begin(115200), and the Serial Monitor is set to 9600 baud. What do you see, and how do you fix it?
Show answer
You see garbled or meaningless characters, because the two sides disagree on the speed. Set the Serial Monitor's baud rate dropdown to 115200 so it matches the sketch.
Exercise
Write a loop body that prints Count: 0, Count: 1, Count: 2, and so on, one per line, once per second. Which function leaves the line open, and which ends it?
Show answer
Declare int count = 0; above setup(). In loop(), call Serial.print("Count: "); then Serial.println(count);, then count++; and delay(1000);. Serial.print() leaves the line open, and Serial.println() ends it.
Exercise
You open the Serial Monitor and the first "Setup complete" line is missing, but later lines appear. Why might this happen?
Show answer
Opening the Serial Monitor can restart a board like the Uno. The sketch may have printed the line before the monitor was ready to display it. Press the reset button with the monitor already open to see it again.