The Pi becomes a real sensing platform when you connect sensors. Today you'll read temperature, humidity, distance, and motion data from real hardware.
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.
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 (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.
#!/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.")
csv module for clean output. Add column headers. Run for 1 hour.import matplotlib.pyplot as plt; plt.plot(times, temps); plt.savefig('temp.png'). Was temperature stable? Did it correlate with time of day?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.