Day 3 of 5
⏱ ~60 minutes
Raspberry Pi in 5 Days — Day 3

Sensors and I2C

The Pi becomes a real sensing platform when you connect sensors. Today you'll read temperature, humidity, distance, and motion data from real hardware.

DHT22: Temperature and Humidity

The DHT22 (also called AM2302) measures temperature (−40 to 80°C, ±0.5°C accuracy) and relative humidity (0–100%, ±2–5% accuracy). It uses a single-wire protocol — one data pin, 3.3V power, ground. Connect a 10kΩ pull-up resistor between data and 3.3V. The sensor takes 2 seconds per reading and can't be read faster. Use Adafruit's CircuitPython DHT library for reliable reading.

HC-SR04: Ultrasonic Distance

The HC-SR04 measures distance by sending an ultrasonic pulse and timing the echo. Trigger pin: send a 10μs HIGH pulse to start a measurement. Echo pin: HIGH for the duration of the echo return. Distance = (echo_duration × speed_of_sound) / 2. Important: HC-SR04 operates at 5V logic, but the Pi's Echo pin expects 3.3V. Use a voltage divider (1kΩ + 2kΩ) on the Echo line to safely drop 5V to 3.3V.

I2C Devices

I2C (Inter-Integrated Circuit) is a two-wire bus (SDA data, SCL clock) that connects multiple devices on the same two wires, each with a unique address. Common I2C sensors: BMP280 (pressure/temp, address 0x76), MPU-6050 (accelerometer/gyro, 0x68), SSD1306 OLED display (0x3C), ADS1115 ADC (0x48). Enable I2C in raspi-config. Use i2cdetect -y 1 to scan for devices and verify addresses.

python
#!/usr/bin/env python3
# Read DHT22 and HC-SR04 sensors
# pip3 install adafruit-circuitpython-dht gpiozero

import time
import board
import adafruit_dht
from gpiozero import DistanceSensor

# ── DHT22 Temperature & Humidity ──────────────────────────
# Wire: VCC→3.3V, GND→GND, Data→GPIO4, 10kΩ pull-up on data
dht = adafruit_dht.DHT22(board.D4, use_pulseio=False)

def read_dht22(retries=3):
    """DHT22 is flaky — retry on failure"""
    for attempt in range(retries):
        try:
            temp = dht.temperature    # Celsius
            humidity = dht.humidity   # %RH
            return temp, humidity
        except RuntimeError as e:
            if attempt < retries-1:
                time.sleep(2)  # DHT22 needs 2s between reads
            else:
                return None, None

# ── HC-SR04 Ultrasonic Distance ──────────────────────────
# Wire: VCC→5V, GND→GND, TRIG→GPIO23, ECHO→voltage divider→GPIO24
sensor = DistanceSensor(echo=24, trigger=23, max_distance=4)

def read_distance():
    dist = sensor.distance  # returns meters
    return dist * 100       # convert to cm

# ── Main Loop: Log sensor data ───────────────────────────
print("Time,Temp(C),Humidity(%),Distance(cm)")
try:
    while True:
        temp, hum = read_dht22()
        dist = read_distance()
        ts = time.strftime('%H:%M:%S')
        if temp and hum:
            print(f"{ts},{temp:.1f},{hum:.1f},{dist:.1f}")
        else:
            print(f"{ts},ERROR,ERROR,{dist:.1f}")
        time.sleep(3)
except KeyboardInterrupt:
    dht.exit()
    print("Stopped.")
💡
DHT22 readings fail about 10% of the time due to the timing-sensitive protocol. Always wrap reads in a try/except and retry. Also wait 2 seconds between reads — the sensor can't sample faster. For production reliability, upgrade to an SHT31 (I2C, far more reliable) or BME280.
📝 Day 3 Exercise
Build a Multi-Sensor Data Logger
  1. Wire a DHT22 to GPIO4. Test with the read script. Record temperature and humidity every 30 seconds to a CSV file.
  2. Add an HC-SR04 distance sensor. Wire TRIG→GPIO23, ECHO→voltage divider→GPIO24. Verify distance readings match a ruler.
  3. Combine both sensors: log timestamp, temperature, humidity, and distance to the same CSV.
  4. Use Python's csv module for clean output. Add column headers. Run for 1 hour.
  5. Analyze the data: plot temperature over time with import matplotlib.pyplot as plt; plt.plot(times, temps); plt.savefig('temp.png'). Was temperature stable? Did it correlate with time of day?

Day 3 Summary

  • DHT22 reads temp/humidity on a single data pin — retry on failure, 2s minimum between reads
  • HC-SR04 uses 5V logic — protect Pi's 3.3V Echo pin with a 1kΩ+2kΩ voltage divider
  • I2C connects multiple sensors on two wires (SDA/SCL); use i2cdetect to find device addresses
  • Log sensor data to CSV for later analysis — timestamp + readings, one row per sample
Challenge

Connect an SSD1306 128×64 OLED display (I2C, ~$5 on Amazon) to the Pi. Use the luma.oled library to display live sensor readings on the screen — temperature on line 1, humidity on line 2, distance on line 3. Update every 2 seconds. This is a complete standalone sensor display device.

Finished this lesson?