Sub topic 4
Printing text and values with print and println
This chapter covers Serial.print() and Serial.println(): what each one sends, how it handles different data types, and the mistakes that cause confusing output. It assumes you can already write a basic sketch with setup() and loop(), upload it from the Arduino IDE, and use variables, data types and if statements in C/C++. It also assumes you have used analogRead() and digitalWrite(). You should have already called Serial.begin() and opened the Serial Monitor at a matching baud rate.
What print and println do
Serial.print() sends data out of the board's serial port as text. The Serial Monitor shows that text on the computer. Serial.println() does the same and then sends two extra characters, a carriage return (\r) and a newline (\n). The Serial Monitor starts a new line when it receives them.
The only difference between the two is that line ending. Use print() to build a line from several pieces. Use println() for the last piece, so the next output starts on a fresh line.
void setup() {
Serial.begin(9600);
Serial.print("Hello, ");
Serial.print("world");
Serial.println("!");
Serial.println("This is a new line.");
}
void loop() {
}The Serial Monitor shows this:
Hello, world!
This is a new line.Each call returns the number of bytes it wrote, as a size_t. You rarely need that value, but it is useful when you want to align columns or check how much data you queued.
Data types you can print
print() and println() are overloaded. The compiler picks a version based on the type of the argument, and each version formats the value differently.
| Argument type | Example | What is sent |
|---|---|---|
| String literal | `Serial.print("on")` | The characters `on` |
| `char` | `Serial.print('A')` | The single character `A` |
| `int`, `long` and their unsigned forms | `Serial.print(42)` | The digits `42`, not the byte value 42 |
| `float`, `double` | `Serial.print(3.14159)` | `3.14` (two decimal places by default) |
| `bool` | `Serial.print(true)` | `1` |
| `String` object | `Serial.print(name)` | The characters in the string |
| `char` array | `Serial.print(buffer)` | Characters up to the terminating zero |
Two details in this table cause most beginner confusion.
First, numbers are converted to readable text. Serial.print(65) sends the two characters 6 and 5. It does not send the letter A. If you want the single byte with value 65 on the wire, use Serial.write(65). The Serial Monitor then displays A because it interprets that byte as an ASCII character.
Second, a float prints with two decimal places unless you ask for more. A value of 0.004 prints as 0.00, which can look like a broken sensor when it is only rounding.
Characters versus numbers
A char is a number that the compiler treats as a character when you print it. You can see both views of the same value:
void setup() {
Serial.begin(9600);
char letter = 'A';
Serial.println(letter); // A
Serial.println((int)letter); // 65
Serial.println(letter + 1); // 66
Serial.println((char)(letter + 1)); // B
}
void loop() {
}The third line prints 66 and not B. In C++, adding an int to a char produces an int, so the overload for integers runs. Cast the result back to char when you want a letter.
Building one readable line
A single line of output usually combines a label and a value. Chain print() calls and finish with println():
int counter = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print("count = ");
Serial.println(counter);
counter++;
delay(1000);
}Output:
count = 0
count = 1
count = 2Labels matter once you print more than one value. Compare 12 340 5 with temp=12 light=340 button=5. The second version stays readable when you return to it a week later.
Separators
Choose a separator and use it consistently. A comma or a tab keeps values apart, and a consistent separator also makes the output easy to paste into a spreadsheet or parse later. You can send a tab with the escape sequence \t.
void setup() {
Serial.begin(9600);
Serial.println("ms\tA0\tA1");
}
void loop() {
Serial.print(millis());
Serial.print('\t');
Serial.print(analogRead(A0));
Serial.print('\t');
Serial.println(analogRead(A1));
delay(500);
}The header row, printed once in setup(), names each column. Printing a single char such as '\t' is slightly cheaper than printing a one-character string, because the string needs a terminator and a pointer to it.
Call order and where the newline goes
Output appears in the order of the calls. A common mistake is to use println() where print() was intended, so every value lands on its own line:
// Intended: one line per reading
Serial.println("temp=");
Serial.println(25);This prints temp= and 25 on separate lines. Replace the first println() with print() to fix it.
The opposite mistake is to use print() for the last piece. Nothing marks the end of the line, so the next loop iteration continues on the same line and the output turns into one long string.
void loop() {
Serial.print("value=");
Serial.print(analogRead(A0)); // no newline: lines run together
delay(500);
}The Serial Monitor shows value=512value=514value=513. Change the second call to println().
Printing a blank line and special characters
Serial.println() with no argument sends only the line ending, which gives you a blank line. This is a cheap way to separate groups of output.
Escape sequences work inside string literals and char constants:
| Sequence | Meaning |
|---|---|
| `\n` | Newline |
| `\r` | Carriage return |
| `\t` | Tab |
| `\\` | A backslash |
| `\"` | A double quote inside a string |
Use \n carefully. The Serial Monitor treats a lone \n as a line break, but some other terminal programs need \r\n. println() always sends both, which is why it is the safer choice.
Combining print with number base and precision
Both functions accept an optional second argument. For integers it selects the base (DEC, HEX, OCT, BIN). For floats it sets the number of decimal places. The next chapter covers this in detail, so this section only shows the call shape:
void setup() {
Serial.begin(9600);
Serial.println(42); // 42
Serial.println(42, HEX); // 2A
Serial.println(3.14159, 3); // 3.142
}
void loop() {
}Common errors
Most problems with print() come from a small set of causes.
- Garbage characters. The sketch and the Serial Monitor use different baud rates. Match the value in
Serial.begin()to the drop-down at the bottom of the monitor. - Everything on one line. You used
print()where you neededprintln(), or the Serial Monitor's line-ending setting does not suit what you are sending. - A number appears as a letter, or a letter as a number. You mixed
print()andwrite(), or you added to acharwithout casting. - A float shows
0.00or-0.00. The default precision is two decimal places. Pass a second argument, for exampleSerial.println(value, 4). ovforinfappears instead of a number. Floating-point values that are too large to print, or the result of dividing by zero, produce text such asovf,infornan. Check the calculation, not the printing.- Integer division gives the wrong value.
Serial.println(1 / 2)prints0, because both operands are integers. Write1.0 / 2to get0.50. - Output stops after a few lines. Too much printing can fill the transmit buffer and slow the sketch. Later chapters cover this cost.
Seeing the difference between print and write
Because the distinction between text and raw bytes is a frequent source of errors, the following sketch prints the same value both ways:
void setup() {
Serial.begin(9600);
Serial.print(72); // sends "72" (two characters)
Serial.println();
Serial.write(72); // sends one byte, shown as H
Serial.println();
}
void loop() {
}Expected output:
72
HUse print() for anything a person will read. Use write() when another program expects raw bytes.
Summary of when to use each call
- Use
Serial.print()for each part of a line except the last. - Use
Serial.println()for the last part, or alone for a blank line. - Use
Serial.write()for raw bytes. - Label every value, and use one separator throughout.
- Add a second argument when you need a different number base or more decimal places.
Exercise
A sketch runs int x = 7; Serial.print("x is "); Serial.print(x); inside loop() with a one-second delay. The Serial Monitor shows x is 7x is 7x is 7 on one line. What change fixes it, and what would Serial.println('A' + 1) print?
Show answer
Change the second call to Serial.println(x); so a line ending follows each reading. 'A' + 1 is an int with value 66, so Serial.println('A' + 1) prints 66, not B. Cast with (char)('A' + 1) to print B.
Exercise
Write a loop body that prints one line per second in the form t=1234 ms, A0=512, using a label for each value. Which calls use print() and which uses println()?
Show answer
Use Serial.print("t=");, Serial.print(millis());, Serial.print(" ms, A0="); and finally Serial.println(analogRead(A0)); followed by delay(1000);. Every call except the last is print(). The last is println() because it ends the line.