Day 03 Applied Skills

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.

~1 hour Hands-on Precision AI Academy

Today's Objective

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

01

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.

02

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.

03

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

Supporting References & Reading

Go deeper with these external resources.

Docs
Sensors and I2C Official documentation for raspberry pi.
GitHub
Sensors and I2C Open source examples and projects for Sensors and I2C
MDN
MDN Web Docs Comprehensive web technology reference

Day 3 Checkpoint

Before moving on, confirm understanding of these key concepts:

Continue To Day 4
Day 4 of the Raspberry Pi in 5 Days course