Sub topic 13
Displaying and logging readings
This chapter covers how to get DHT readings out of the Arduino in a form that people and programs can both use. It assumes you can already read the sensor with dht.readTemperature() and dht.readHumidity(), check results with isnan(), and pace reads with millis(). It also assumes you can upload a sketch and open the Serial Monitor. The Python example needs Python 3 with the pyserial package.
Choose the output for the audience
The same two numbers can go to several places. Pick the destination first, because it decides the format.
| Destination | Best for | Format | Main limit |
|---|---|---|---|
| Serial Monitor | Debugging while the board is on your desk | Readable text | Nothing is saved |
| Serial Plotter | Watching trends and checking sensor behavior | `label:value` pairs | Short history, no saving |
| Host program over USB | Long logs on a computer | CSV lines | The computer must stay connected |
| 16x2 character display | A standalone readout | Short fixed-width text | 16 characters per line |
| SD card module | Logging with no computer | CSV file | Extra wiring and a library |
This chapter works through the first three in detail. The last two follow the same ideas and are covered briefly at the end.
Design the line format before writing code
Serial output is a stream of text lines. Whatever reads it has to split each line back into values, so the format is an interface. Three rules keep that interface reliable:
- One reading per line. End each reading with
println(), so a reader can treat each line as a record. - A fixed separator and fixed field order. Use a comma, with temperature first and humidity second, and never change that order.
- Separate data from messages. Errors and status text should be easy to tell apart from data. A common convention is to start them with
#, so a parser can skip them.
The DHT22 reports with 0.1 resolution. Serial.print(float) prints two decimals by default, which implies precision the sensor does not have. Pass the number of decimals as a second argument: Serial.print(temperatureC, 1).
A logging-ready sketch
This sketch combines the earlier chapters: non-blocking timing, NaN checks, and a CSV-style output. It prints a header once at startup and one data line per successful read.
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
const unsigned long READ_INTERVAL_MS = 2000;
unsigned long lastReadMs = 0;
void setup() {
Serial.begin(9600);
dht.begin();
Serial.println(F("temperature_c,humidity_pct"));
}
void loop() {
unsigned long now = millis();
if (now - lastReadMs >= READ_INTERVAL_MS) {
lastReadMs = now;
float humidity = dht.readHumidity();
float temperatureC = dht.readTemperature();
if (isnan(humidity) || isnan(temperatureC)) {
Serial.println(F("# read failed"));
} else {
Serial.print(temperatureC, 1);
Serial.print(',');
Serial.println(humidity, 1);
}
}
}Open the Serial Monitor at 9600 baud and you should see output like this:
temperature_c,humidity_pct
22.4,48.1
22.4,48.2
# read failed
22.5,48.0The F() macro keeps the string constants in flash instead of RAM. On an Uno with 2 KB of RAM, this matters once a sketch has many messages.
Why the failure message starts with a hash
A failed read could print nan,nan. That is a valid-looking CSV line, and many spreadsheet tools and parsers will either reject it or store text in a numeric column. A # line is ignored by the logger below, and a person scanning the Serial Monitor still sees it. The failure is visible in the monitor but absent from the data file.
If you need to know when gaps happened, record the time of each good reading rather than logging the gap. Gaps then show up as jumps in the timestamps.
Plot the readings with the Serial Plotter
The Arduino IDE's Serial Plotter draws a live graph from serial text. It accepts lines of label:value pairs separated by commas, one line per sample. This helper prints in that format:
void printForPlotter(float temperatureC, float humidity) {
Serial.print(F("Temperature:"));
Serial.print(temperatureC, 1);
Serial.print(',');
Serial.print(F("Humidity:"));
Serial.println(humidity, 1);
}Call it in place of the CSV prints inside the success branch. Each label becomes its own line on the graph with its own color.
Plotter output and CSV output are different formats. Do not mix them in one sketch run, and remove the header line when plotting. A text header line is not a valid sample.
A plot also shows problems that are hard to see in text. A smooth line with 0.1 steps is normal. Repeated spikes to 0 or to very high values suggest a loose wire, a missing pull-up resistor, or a read interval that is too short.
Log to a file on a computer
The Serial Monitor does not save anything. To keep a record, write a small program on the computer that reads the serial port. This Python script appends each good reading to log.csv with a timestamp from the computer's clock:
import csv
import sys
from datetime import datetime
import serial # pip install pyserial
PORT = sys.argv[1] # for example COM3 or /dev/ttyACM0
BAUD = 9600
LOG_FILE = "log.csv"
with serial.Serial(PORT, BAUD, timeout=5) as ser, \
open(LOG_FILE, "a", newline="") as f:
writer = csv.writer(f)
if f.tell() == 0:
writer.writerow(["timestamp", "temperature_c", "humidity_pct"])
while True:
raw = ser.readline().decode("ascii", errors="ignore").strip()
if not raw or raw.startswith("#"):
continue
parts = raw.split(",")
if len(parts) != 2:
continue
try:
temperature = float(parts[0])
humidity = float(parts[1])
except ValueError:
continue # the header line and any garbled line end up here
writer.writerow([datetime.now().isoformat(timespec="seconds"),
temperature, humidity])
f.flush()
print(raw)Run it with python logger.py /dev/ttyACM0, using your own port name.
The script does three things deliberately:
- It skips blank lines, comment lines, and lines that do not have exactly two fields. Serial links can deliver a partial first line if the script starts while the board is mid-print.
- It converts with
float()inside atryblock, so the Arduino's header line and any corrupted line are dropped instead of crashing the logger. - It calls
f.flush()after each row, so a power loss or a killed process loses at most the last row.
The timestamp comes from the computer because the Arduino has no real-time clock. The Arduino's millis() only counts from the last reset, and it also overflows after about 49.7 days.
Serial port gotchas
- One program per port. If the Serial Monitor, Serial Plotter, or another script has the port open, the logger fails to open it, or the two programs lose data to each other. Close the Arduino IDE's monitor first.
- Opening the port often resets the board. On Uno-style boards, opening a serial connection toggles the DTR line and reboots the sketch. That is why the header line reappears each time the logger starts. The logger's header filter handles it. Keep this in mind if you log for days, since restarting the logger resets the Arduino too.
- Baud mismatch gives garbage. The value in
Serial.begin()and theBAUDconstant in the script must match. Garbled characters in the monitor usually mean they do not. - Port names change. On Linux and macOS the name can change when you replug the cable. On Windows the COM number can differ between USB ports.
Stand-alone options
If the project cannot depend on a computer, two outputs replace the serial link.
Character LCD. A 16x2 display with an I2C backpack needs only two data wires and shows two lines of 16 characters. Format your text to fit, for example T:22.4C H:48.1%, which is 15 characters. Rewrite the same screen positions each cycle instead of clearing the whole display, because clearing causes visible flicker. I2C backpacks use different addresses, commonly 0x27 or 0x3F, so check yours with an I2C scanner sketch.
SD card. An SD module writes the same CSV lines to a file with no computer attached. Because the board has no clock, add an RTC module such as a DS3231 if you need timestamps, or log the elapsed seconds from millis() and note the start time yourself. Call flush() or close the file after each write, so a power cut does not lose buffered rows. Writing once every few seconds is gentle on the card. Logging every loop pass is not.
Choose a logging interval separate from the read interval
The DHT22 can be read every 2 seconds, but that does not mean you should log every 2 seconds. Room temperature changes slowly. Logging every 2 seconds for a day produces 43,200 rows, almost all of them nearly identical, and a plot of that is hard to read.
A simple pattern is to keep the 2-second read cycle and write a log line every Nth good reading. Or you can average N readings and log the mean, which also smooths sensor noise. Choose the interval from how fast the quantity you care about changes: seconds for a hot-air gun test, minutes for a room, and 10 to 15 minutes for long-term weather records.
Common mistakes
- Printing text labels such as
Temperature: 22.4and then trying to parse that line as CSV. Keep human-readable and machine-readable output separate, or choose the machine format and accept a plainer display. - Forgetting
printlnon the last field, so the whole log arrives as one long line. - Logging calibrated values in some rows and raw values in others after changing the offset. Record the offset you used, for example in a comment line at startup, so old data stays interpretable.
- Using
Serial.print(float)with no decimal count and ending up with columns such as22.40that suggest more precision than the sensor has.
Exercise
Your logger script crashes with a ValueError after you edit the sketch so that failed reads print nan,nan. Why does it happen, and what are two ways to fix it?
Show answer
Python's float() accepts the string "nan", so a nan,nan line would not crash it, but it would write NaN values into the CSV. A crash with ValueError happens when a line has the right number of fields but one is not numeric, such as the header temperature_c,humidity_pct or a partial line. Fix it either by catching ValueError (as the script does) and skipping the line, or by having the sketch print failures as # comment lines so the parser ignores them. The second approach also keeps NaN values out of the file, so it is usually better.
Exercise
You want a log row every 5 minutes, but the sensor is read every 2 seconds. Describe how to do it with a counter in the sketch, and state how many good readings that is.
Show answer
Five minutes is 300 seconds, so 300 / 2 = 150 readings. Keep a counter that increases on each good reading, and print a CSV line when it reaches 150, then reset it to 0. Alternatively, add each good reading to running sums, and when the counter reaches 150, print the sum divided by 150 for each value and reset the sums. The averaged version smooths noise.