Sub topic 8
Displaying Sensor Readings Clearly
What this chapter assumes
You should already know how to start serial with Serial.begin() and open the Serial Monitor at the same baud rate. You should also know Serial.print() and Serial.println(), and how to pass a second argument to set decimal places. You need analogRead() and basic C++ types (int, long, float). This chapter uses those pieces to make sensor output that you can read at a glance and reuse later.
Why a bare number is not enough
This sketch compiles and runs, but its output is hard to use:
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println(analogRead(A0));
delay(500);
}The Serial Monitor shows a column like 512, 514, 511. You cannot tell what the number means, which pin it came from, or whether it is a raw count or a voltage. With two sensors you cannot tell which line belongs to which. A readable display answers four questions on every line:
- Which sensor is this?
- Is the value raw or converted?
- What unit is it in?
- Is the precision sensible?
From raw counts to volts
analogRead() returns a count, not a voltage. On an Uno the analog-to-digital converter (ADC) has 10 bits, so it returns an integer from 0 to 1023. A reading of 0 means 0 V and 1023 means the reference voltage. By default the reference voltage is the board's supply voltage, which is 5 V on an Uno and 3.3 V on many other boards.
The conversion is:
volts = raw * (reference / 1023)This sketch prints the label, the raw count, and the voltage on one line:
const int SENSOR_PIN = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
int raw = analogRead(SENSOR_PIN);
float volts = raw * (5.0 / 1023.0); // assumes a 5 V reference
Serial.print(F("raw="));
Serial.print(raw);
Serial.print(F(" volts="));
Serial.println(volts, 2);
delay(500);
}A typical line is raw=512 volts=2.50. Three things make it clear:
print()is used for every piece except the last, andprintln()ends the line. Each sample therefore occupies exactly one line.- Each value has a label (
raw=,volts=) written as anF()string, so the labels do not use RAM. volts, 2limits the float to two decimal places. Without it,Serial.print(float)also prints two places by default, but writing the number states your intent.
Integer division and overflow
Two arithmetic mistakes account for most wrong sensor values.
The first is integer division. In C++, 5 / 1023 with two integers evaluates to 0, because the fraction is discarded before anything else happens:
float wrong = raw * (5 / 1023); // always 0
float right = raw * (5.0 / 1023.0); // correctAt least one operand must be a floating-point number. Writing 5.0 is enough.
The second is overflow. On an Uno, int is 16 bits and holds at most 32767. If you want millivolts and write raw * 5000 / 1023, the product raw * 5000 reaches about 5,115,000 and wraps around. Promote one operand to long first:
long millivolts = (long)raw * 5000 / 1023;This stays in integers, so it is fast and exact enough for display. Boards with 32-bit int (such as the Due or ESP32) do not overflow here, but the cast does no harm.
Converting to a physical unit
Volts are rarely what you want to read. A TMP36 temperature sensor outputs 10 mV per °C with a 500 mV offset, so 0 °C is 0.5 V. The conversion adds one line to the previous formula:
celsius = (volts - 0.5) * 100This sketch prints a header once in setup(), then one comma-separated line per sample:
const int SENSOR_PIN = A0;
const float REF_VOLTS = 5.0;
void setup() {
Serial.begin(9600);
Serial.println(F("raw,volts,celsius"));
}
void loop() {
int raw = analogRead(SENSOR_PIN);
float volts = raw * (REF_VOLTS / 1023.0);
float celsius = (volts - 0.5) * 100.0;
Serial.print(raw);
Serial.print(',');
Serial.print(volts, 3);
Serial.print(',');
Serial.println(celsius, 1);
delay(500);
}The output looks like this:
raw,volts,celsius
152,0.743,24.3
153,0.748,24.8Compare the precision choices. The raw count is an exact integer. The voltage gets three decimals because one ADC step on a 5 V board is about 4.9 mV, so a third decimal is the most the hardware can resolve. The temperature gets one decimal because the sensor itself is only accurate to about ±1 °C. Printing 24.31837 would suggest accuracy you do not have.
Choosing a line format
How you lay out a line depends on who reads it. A person reading the Serial Monitor wants labels and units. A program, or the Serial Plotter covered later, wants a predictable structure.
| Format | Example | Best for | Drawback |
|---|---|---|---|
| Labeled text | `raw=152 volts=0.74` | Reading in the Serial Monitor | Harder to parse in a script |
| CSV with header | `152,0.743,24.3` | Pasting into a spreadsheet | Needs the header to make sense |
| `label:value` pairs | `A0:152,A1:610` | Serial Plotter, multiple sensors | Less readable with many values |
Pick one format per sketch and keep it. Switching format mid-sketch breaks spreadsheets and plotters, and it makes your own output harder to scan.
Reducing jitter before you print
An unconnected or noisy input makes the last digit flicker between samples. If you print every raw sample you see a nervous display, and you may mistake noise for a real change. Averaging a few readings gives a steadier number:
const int SENSOR_PIN = A0;
const int SAMPLES = 8;
int readAveraged(int pin, int samples) {
long sum = 0;
for (int i = 0; i < samples; i++) {
sum += analogRead(pin);
}
return sum / samples;
}
void setup() {
Serial.begin(9600);
}
void loop() {
int raw = readAveraged(SENSOR_PIN, SAMPLES);
float volts = raw * (5.0 / 1023.0);
Serial.print(F("avg raw="));
Serial.print(raw);
Serial.print(F(" volts="));
Serial.println(volts, 2);
delay(500);
}sum is a long so that eight readings of up to 1023 cannot overflow. Label the line avg raw so that you remember the value is processed. If you later compare it with a single analogRead(), you will know why the two differ.
Common display mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| Voltage is always `0.00` | Integer division such as `5 / 1023` | Use `5.0 / 1023.0` |
| Values jump to large negative numbers | `int` overflow in a millivolt calculation | Cast to `long` before multiplying |
| Everything appears on one long line | Only `print()` used, no `println()` | End each sample with `println()` |
| Each value on its own line | `println()` used for every piece | Use `print()` for all but the last |
| Voltage is about 50% too high on a 3.3 V board | Reference constant set to 5.0 | Set the constant to the real reference |
| Last digit flickers | ADC noise | Average samples, or print fewer decimals |
Checklist for a clear display
- Print a label or header so each number identifies itself.
- Put the reference voltage and pin numbers in named constants.
- Show raw and converted values side by side while you develop. Remove the raw value later if you no longer need it.
- Match decimal places to what the sensor can resolve.
- Keep one sample per line and one format per sketch.
- Slow the output down, because a sample every few milliseconds scrolls too fast to read. The
delay(500)above is the simplest way. The next chapter replaces it with amillis()timer so the rest of your sketch keeps running.
Exercise
A student writes float volts = raw * (3.3 / 1023); on an Uno powered from USB (5 V) with a potentiometer on A0, and the Serial Monitor shows 3.30 V when the knob is fully turned up. What is wrong, and what should the line be?
Show answer
The formula assumes a 3.3 V reference, but the Uno's default ADC reference is its 5 V supply. At full scale the raw count is 1023, so the sketch computes 3.3 V instead of the real 5 V. The line should be float volts = raw * (5.0 / 1023.0);. Better, define const float REF_VOLTS = 5.0; and use it in the formula so the value is stated once.
Exercise
Write the line that prints a TMP36 temperature in °C with one decimal place and the label temp=, followed by a space and C, all ending in a newline. Assume celsius is a float.
Show answer
Serial.print(F("temp=")); Serial.print(celsius, 1); Serial.println(F(" C")); The first two calls use print() so the line is not ended early, and the last uses println() to finish it. The output looks like temp=24.3 C.