Sub topic 11
Graphing values with the Serial Plotter
This chapter assumes you can upload a sketch, use Serial.begin, Serial.print, and Serial.println, and read a pin with analogRead. It also assumes you know the baud rate in the sketch must match the one in the Arduino IDE. You will use those skills to draw live graphs of your data.
What the Serial Plotter does
The Serial Plotter is a window in the Arduino IDE that turns numbers arriving over serial into a scrolling line graph. It reads the same stream of bytes as the Serial Monitor. It parses the text you print, finds the numbers, and draws one line for each value on a row.
A graph shows things a column of numbers hides. You can see noise on a sensor, a slow drift, an oscillation, or a sudden spike at a glance. This makes the plotter a good tool for tuning thresholds and checking that a sensor responds the way you expect.
You open it from the Tools menu with Serial Plotter. In the IDE 2.x versions, the plotter and the Serial Monitor cannot both hold the same port at the same time. If you open one, close the other. Select the same baud rate in the plotter's drop-down that you passed to Serial.begin. A mismatch gives garbage that the plotter either skips or draws as meaningless spikes.
How the plotter reads your output
The plotter works on lines. Each time it receives a newline, it treats the text before it as one sample. It splits that text into values and adds one point to each line on the graph.
So two rules control everything:
- End every sample with a newline. Use
Serial.printlnfor the last value on the row. - Separate the values on a row with a comma, a space, or a tab.
If you forget the newline, the plotter never sees the end of a sample. It may show nothing or merge values from different rows.
One value
The simplest case prints one number per line. This draws a single line.
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println(analogRead(A0));
delay(50);
}Connect a potentiometer's middle pin to A0, with the outer pins to 5 V and GND. Turn the knob and the line moves between 0 and 1023.
Several values with labels
To draw more than one line, print several values on the same row. To name each line in the legend, put a label and a colon in front of each value.
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print("A0:");
Serial.print(analogRead(A0));
Serial.print(",");
Serial.print("A1:");
Serial.println(analogRead(A1));
delay(50);
}Each row now looks like A0:512,A1:300. The plotter reads A0 and A1 as series names and draws two colored lines. The legend shows the names. Only the last call uses println, so the newline arrives once per row.
A label can contain letters, digits, and underscores. Avoid spaces inside a label. Because a space can also separate values, a label such as my sensor: may be split into pieces or misread.
The table below summarizes the formats.
| Output on one row | Result |
|---|---|
| `512` | One line, unnamed |
| `512,300` | Two lines, unnamed |
| `A0:512,A1:300` | Two lines named A0 and A1 |
| `512 300` | Two lines, split on the space |
| `A0:512` then a new line | One line named A0 |
Keeping the graph consistent
The plotter keeps a fixed number of recent samples on screen and scrolls as new ones arrive. It also rescales the vertical axis to fit the values it sees. This causes two problems you will notice early.
The number of values per row must stay constant
If one row has two values and the next has three, the graph can flicker or mix up which line is which. Always print the same labels in the same order. Do not add a value to a row only when some condition is true. Print a placeholder, such as the previous value or zero, instead.
The axis rescales as values change
If your data ranges from 0 to 1023, the axis fits that. If a single spike jumps to 5000, the whole axis stretches and the normal data flattens at the bottom. Two fixes are common:
- Limit or clamp the values before printing, for example with
constrain. - Print fixed reference lines so the axis stays stable. You print them as extra labeled series that never change.
The sketch below draws the sensor reading between two constant lines at 0 and 1023. The plotter keeps the axis from collapsing around a small signal, and you can see how close the reading is to its limits.
const int SENSOR_PIN = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
int raw = analogRead(SENSOR_PIN);
Serial.print("Min:");
Serial.print(0);
Serial.print(",");
Serial.print("Max:");
Serial.print(1023);
Serial.print(",");
Serial.print("Sensor:");
Serial.println(raw);
delay(50);
}Mixing different scales
Suppose you plot a raw reading (0 to 1023) and a voltage (0 to 5) on the same graph. The voltage line sits flat near zero, because the axis is sized for the larger series. Scale the values onto a common range before printing. For example, print volts * 200 so the two series are of similar size, and state the factor in the label, such as Volts_x200:.
Choosing the sample rate
How often you print decides how the graph looks. Printing every few milliseconds fills the window with a very fast-moving trace. Printing once a second makes a graph that updates too slowly to follow changes.
A rate of 20 to 100 samples per second suits most sensor work. A delay(50) gives 20 samples per second, which is what the earlier examples use. If the rest of your sketch has other tasks, avoid delay and use the millis() pattern from the chapter on timed output so the loop keeps running.
unsigned long lastSample = 0;
const unsigned long SAMPLE_INTERVAL = 50;
void setup() {
Serial.begin(115200);
}
void loop() {
unsigned long now = millis();
if (now - lastSample >= SAMPLE_INTERVAL) {
lastSample = now;
Serial.print("Light:");
Serial.println(analogRead(A0));
}
// other work can run here without being blocked
}This example uses 115200 baud. A higher baud rate sends each row faster, which helps when you print many series quickly. Whatever you choose, set the plotter to the same speed.
Plotting derived values
You can plot more than raw readings. Printing a computed value beside the raw one shows what your code is doing to the signal. A common example is a smoothed value next to the noisy input.
float smoothed = 0;
const float ALPHA = 0.1; // lower = smoother, slower to react
void setup() {
Serial.begin(115200);
smoothed = analogRead(A0);
}
void loop() {
int raw = analogRead(A0);
smoothed = smoothed + ALPHA * (raw - smoothed);
Serial.print("Raw:");
Serial.print(raw);
Serial.print(",");
Serial.print("Smoothed:");
Serial.println(smoothed, 1);
delay(20);
}The smoothed line follows the raw line but with the jitter removed. Changing ALPHA and watching the graph is a quick way to find a value that suits your sensor. The second argument of Serial.println(smoothed, 1) limits the float to one decimal place, as covered in the number formats chapter.
The plotter and debug text do not mix
The plotter tries to parse everything it receives. A line like Setup complete has no number, so it may produce a gap, a zero, or an error in the legend. The same happens with any other text that is not a label:value pair.
Follow these habits:
- Remove or disable other
Serial.printdebug messages while you use the plotter. - If you use the conditional macros from the earlier chapter, set
DEBUGto 0 before plotting. - Print only the series you want on each row.
Do not rely on a diagram here. The flow is short enough to describe in words: your sketch prints a row, the IDE splits it on commas, spaces, or tabs, and the plotter adds one point to each named line.
Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| The graph is empty | Plotter baud rate differs from `Serial.begin`, or no newline was printed | Match the rates and end each row with `println` |
| Lines swap or flicker | The number or order of values changes between rows | Print the same labels in the same order every time |
| A flat line at the bottom | A large spike or a second series with much bigger values stretched the axis | Clamp values or rescale series |
| Strange legend names | A label contains a space or a character other than letters, digits, or underscore | Use underscores in labels |
| Port busy when opening | The Serial Monitor is open on the same port | Close the Serial Monitor, then open the plotter |
| Graph looks jerky | Printing is too slow or too fast | Adjust the interval to 20 to 100 samples per second |
Summary
The Serial Plotter reads the same serial stream as the Serial Monitor but draws numbers instead of text. Print one row per sample, end it with a newline, and separate values with commas. Add label: before each value to name the lines. Keep the number of values constant, keep the scales similar, and keep stray text out of the stream.
Exercise
Write the loop() body that plots a sensor on A0 and a threshold constant of 600, with the names "Sensor" and "Threshold", 20 times per second. Which call must be println, and why?
Show answer
Use this code in loop(): Serial.print("Sensor:"); Serial.print(analogRead(A0)); Serial.print(","); Serial.print("Threshold:"); Serial.println(600); delay(50);. The last value call must be Serial.println, because the newline marks the end of a sample. Without it, the plotter does not know where one row stops and the next begins.
Exercise
A plot of two series shows a flat line near zero for one of them while the other moves widely. The first series is a voltage from 0 to 5 and the second is a raw reading from 0 to 1023. What is the cause and how can you fix it?
Show answer
The vertical axis is sized for the larger series, so the 0 to 5 values look flat. Multiply the voltage by a factor such as 200 before printing, so it spans roughly 0 to 1000, and put the factor in the label, for example Volts_x200:. Alternatively, plot the voltage on its own.