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
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)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.