Sub topic 8
Watching readings in the Serial Monitor
The Serial Monitor is how you see what analogRead() returns while the sketch runs. This chapter covers how the board sends text to your computer, how to format potentiometer readings, how to use the Serial Plotter, and what usually goes wrong.
This chapter assumes you can upload a sketch and open the Serial Monitor, and that the potentiometer is already wired to A0 as in the previous chapter. It also assumes you know setup() and loop().
How serial output reaches your screen
An Arduino Uno has a hardware serial port (a UART). It sends one byte at a time as a series of voltage pulses. On the Uno, a helper chip on the board converts those pulses to USB, so the computer sees a virtual serial port. Boards with native USB, such as the Leonardo, expose the port directly. The Serial Monitor in the Arduino IDE opens that port and displays each byte as a character.
Two consequences follow from this path:
- Everything you print is converted to text. The number
512travels as the three characters5,1,2, followed by a newline. - Both ends must agree on the speed. That speed is the baud rate, in bits per second.
Starting the port: Serial.begin()
Call Serial.begin() once in setup():
void setup() {
Serial.begin(9600);
}The number is the baud rate. The drop-down at the bottom right of the Serial Monitor must show the same value. If the two differ, you will see unreadable symbols or nothing at all.
9600 is a common default and is plenty for a potentiometer. A reading such as raw=1023 volts=5.00 is about 20 characters. Each character takes about 10 bits on the wire (8 data bits plus a start bit and a stop bit), so 9600 baud carries roughly 960 characters per second. That is far more than a sketch printing 10 lines per second needs. Higher rates such as 115200 are useful when you print many values quickly.
The first monitoring sketch
This sketch reads A0, converts the reading to volts with a 5 V reference as on an Uno, and prints both.
const int POT_PIN = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
int raw = analogRead(POT_PIN);
float volts = raw * (5.0 / 1023.0);
Serial.print("raw=");
Serial.print(raw);
Serial.print(" volts=");
Serial.println(volts, 2);
delay(100);
}Upload it, open the Serial Monitor, and set the baud rate to 9600. Turn the knob slowly. You should see output like this:
raw=0 volts=0.00
raw=212 volts=1.04
raw=512 volts=2.50
raw=1023 volts=5.00If the knob is wired correctly, one end of its travel gives values near 0 and the other end gives values near 1023. If the readings run backwards, swap the two outer wires.
What each print call does
Serial.print() sends text without a line ending. Serial.println() sends the text and then a carriage return and a newline, so the next output starts on a new line. Build one line from several print calls and finish it with println.
The second argument changes how a number is formatted:
| Call | Output for the value 512 or 2.5 |
|---|---|
| `Serial.print(512)` | `512` |
| `Serial.print(512, HEX)` | `200` |
| `Serial.print(512, BIN)` | `1000000000` |
| `Serial.print(2.5)` | `2.50` (floats default to two decimals) |
| `Serial.print(2.5, 3)` | `2.500` |
| `Serial.print(2.5, 0)` | `3` (rounded to zero decimals) |
For floating-point values the second argument is the number of decimal places. For integers it is the number base. Passing 2 to a float and passing 2 to an integer therefore mean different things.
Decimal places carry no extra information beyond the ADC's precision. One step on a 5 V, 10-bit reading is about 0.0049 V, so printing volts with 2 decimals is enough. Printing 6 decimals only shows rounding artifacts.
Saving memory with F()
String literals such as "raw=" are copied into RAM on AVR boards like the Uno, which has only 2 KB. Wrapping a literal in F() keeps it in flash instead:
Serial.print(F("raw="));This does not matter for a tiny sketch. It starts to matter when a program prints many labels.
Pacing the output with delay()
loop() runs thousands of times per second. Without a delay(), the sketch prints far more lines than you can read, and it can outrun the serial port. The UART sends bytes at a fixed rate, and Serial.print() stores outgoing bytes in a small buffer. On AVR boards that buffer is 64 bytes. When it is full, print() waits until space is free, which slows the whole loop to the baud rate.
The delay(100) in the example above gives about 10 readings per second, which is comfortable to read. Pick the delay from how fast you need to see changes, not from how fast the ADC can run.
Plotting with the Serial Plotter
Numbers in a column are hard to judge when a value changes smoothly. The Arduino IDE has a Serial Plotter (under Tools) that draws printed values as a live graph. It reads the same serial stream, so you do not need extra libraries.
The plotter understands lines with one or more numbers. For several series, put a label, a colon, and a value for each, separated by commas, and end the line with a newline:
const int POT_PIN = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
int raw = analogRead(POT_PIN);
Serial.print("raw:");
Serial.print(raw);
Serial.print(",min:0,max:1023");
Serial.println();
delay(20);
}The constant min and max series hold the vertical axis steady, so the graph does not rescale every time the knob moves. A plain-text label such as raw= would confuse the plotter. Use the plotter for shape and the Serial Monitor for exact values, and do not leave both open at once, because only one program can hold the port.
Reducing clutter: print only changes
If the potentiometer sits still, the output repeats the same line, or jitters by a count or two. The deadband idea, covered fully in a later chapter, can be previewed here. This sketch prints only when the value moves by at least a threshold:
const int POT_PIN = A0;
const int THRESHOLD = 4;
int lastReported = -1;
void setup() {
Serial.begin(9600);
}
void loop() {
int value = analogRead(POT_PIN);
if (lastReported < 0 || abs(value - lastReported) >= THRESHOLD) {
lastReported = value;
Serial.println(value);
}
delay(20);
}The lastReported < 0 test makes the first reading always print, because the starting value of -1 can never be a real ADC result. Here the quiet output is the point: you can tell the moment the knob moves.
Common problems and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| Garbage characters such as `âÿ` | Baud rate in the monitor differs from `Serial.begin()` | Set the drop-down to the same value |
| Nothing appears | Wrong port or board selected, or `Serial.begin()` is missing | Check Tools > Port and Tools > Board, and add `Serial.begin()` |
| Output restarts when the monitor opens | Opening the port resets an Uno | Expected. Wait a moment for the sketch to restart |
| Everything runs together on one line | `print()` used where `println()` was needed | End each record with `println()` |
| Values stuck near 0 or 1023, or wandering | Wiring or floating pin, not a serial fault | Re-check the outer terminals and the wiper wire |
| Volts always shows `0.00` or a whole number | Integer division, for example `raw * (5 / 1023)` | Use floating-point literals: `5.0 / 1023.0` |
The last row is a classic. In C++, 5 / 1023 is integer division and gives 0, so the result is always zero. Writing 5.0 makes the expression floating-point. The sketch above is correct because it uses 5.0 / 1023.0.
Debugging habits that pay off
- Print the raw value first. Convert to volts only after the raw numbers look sensible, so you can tell a wiring fault from a math error.
- Label every value.
raw=512is clearer than512when you later add more values. - Test the extremes. Turn the knob fully each way and confirm you reach about 0 and about 1023.
- Remove or reduce the printing once the sketch works. Serial output takes time and, as shown above, can slow a loop that needs to be fast.
Exercise
A sketch prints Serial.println(raw * (5 / 1023)); and the Serial Monitor always shows 0, even though the raw values vary. What is wrong, and how do you fix it?
Show answer
The expression 5 / 1023 uses two integers, so C++ performs integer division and gives 0. Multiplying raw by 0 always gives 0. Use floating-point values instead: Serial.println(raw * (5.0 / 1023.0), 2); which prints the voltage with two decimals.
Exercise
You set Serial.begin(9600) but the Serial Monitor drop-down is set to 115200. What will you see, and how do you fix it?
Show answer
You will see unreadable characters or nothing useful, because the computer samples the incoming bits at a different speed than the board sends them. Change the drop-down to 9600, or change Serial.begin() to 115200 and re-upload. Both must match.
Exercise
Why does the Serial Plotter example print min:0,max:1023 on every line?
Show answer
Printing these two constant series fixes the vertical axis from 0 to 1023. Without them, the plotter rescales its axis to the data, so the graph appears to jump even when the knob barely moves.