Thuta Learning
ProjectsHardwarebeginner

Mini Project Part 2: Temperature Monitor — Python Script & Logging

Relax. We'll talk through this in plain words — no textbook voice.

What you'll walk away with

  • Get comfortable with Mini Project Part 2: Temperature Monitor — Python Script & Logging, no intimidation required
  • Be able to wire the hardware and run the code yourself
  • Apply this concept right away in a real project

Let's think about this for a second

You need to call the DHT22 library's read function repeatedly inside a loop (spacing it out with time.sleep), then print the temperature/humidity value and append it to a log file (implementing the Linux tutorial's >> redirection concept in Python) — since sensor reads can fail intermittently (checksum failures), you'll need try/except to handle errors so the script keeps running instead of crashing.

Let's connect this to a real-world scenario

Writing the log file in CSV format ('timestamp,temperature,humidity\n') makes it easy for the web dashboard in Part 3 to read this data and display it as a graph — use Python's datetime module to add a timestamp, and open('log.csv', 'a') (append mode) to add a new line to the end of the file (this is the Python version of the Linux tutorial's >> concept).

Let's walk through it together

python
import adafruit_dht
import board
import time
import csv
from datetime import datetime

dht = adafruit_dht.DHT22(board.D4)

with open('temp_log.csv', 'a', newline='') as f:
    writer = csv.writer(f)
    while True:
        try:
            temp = dht.temperature
            humidity = dht.humidity
            timestamp = datetime.now().isoformat()
            print(f"{timestamp}: {temp}°C, {humidity}%")
            writer.writerow([timestamp, temp, humidity])
            f.flush()
        except RuntimeError as e:
            print(f"Sensor read error: {e}")  # DHT sensors fail intermittently — this is normal
        time.sleep(5)
You should see
The terminal will print a temperature/humidity reading every 5 seconds, and the history will keep getting written to the temp_log.csv file.

5-Minute Try-It

Run this script yourself (if you have a DHT22 sensor), let it run for a few minutes, then check back on the data in the temp_log.csv file.

A quick word of caution

Using the with open(...) as f: pattern matters because it makes sure the file gets closed properly if you stop the script with Ctrl+C — if you use manual open()/close() instead, the file can end up left open when you hit Ctrl+C.

Easy traps

  • Skipping try/except and having the whole script crash the first time a sensor read error happens (which is intermittent and normal)
  • Skipping f.flush(), so data doesn't show up in the log file right away while the script is running (it's stuck sitting in the buffer)

Now try it yourself

Run this script yourself (if you have a DHT22 sensor), let it run for a few minutes, then check back on the data in the temp_log.csv file.

You'll know it worked when: The terminal will print a temperature/humidity reading every 5 seconds, and the history will keep getting written to the temp_log.csv file.

Mini Project Part 2: Temperature Monitor — Python Script & Logging | Thuta Learning