Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 37 ยท Sensors and Cameras

Temperature and Humidity Sensors

Measure temperature and humidity with a Raspberry Pi: the DS18B20 on 1-Wire, the DHT22 and the BME280 on I2C, with code, logging and averaging.

Temperature is the most popular first sensor for a reason: it is useful, cheap and easy. A Pi can monitor a greenhouse, a fish tank, a server cupboard or a baby's room, and it can log the numbers, draw a chart or send an alert. This lesson covers three widely used parts, how each talks to the Pi, how to read it and how to turn noisy readings into reliable data.

Sensor Measures Interface Notes
DS18B20 Temperature 1-Wire Waterproof versions exist; each chip has a unique ID
DHT22 (AM2302) Temperature and humidity Single wire, own timing Slow: at most one reading every 2 seconds
BME280 Temperature, humidity, pressure I2C or SPI Accurate, small, 3.3 V

Which sensor?

DS18B20 Waterproof, 1-Wire
DHT22 Humidity, cheap
1 / 2

DS18B20 on 1-Wire

The DS18B20 has three pins: ground, power (3.3 V) and data. Connect its data pin to GPIO4 (physical pin 7) and add a 4.7 kilohm pull-up resistor between data and 3.3 V. Enable 1-Wire in raspi-config; the kernel then exposes each sensor as a folder under /sys/bus/w1/devices/, named with a family code 28- followed by the chip's serial number. Reading is just reading a file (read-only):

Terminal
ls /sys/bus/w1/devices/
cat /sys/bus/w1/devices/28-0000075a1c3d/w1_slave

The file has two lines. The first ends with YES when the checksum is valid; the second ends with t= followed by the temperature in thousandths of a degree Celsius:

TEXT
4b 01 4b 46 7f ff 05 10 e1 : crc=e1 YES
4b 01 4b 46 7f ff 05 10 e1 t=20687

That is 20.687 degrees Celsius. In Python (read-only):

Python
from pathlib import Path
raw = Path("/sys/bus/w1/devices/28-0000075a1c3d/w1_slave").read_text()

gpiozero also provides W1ThermSensor-like helpers via the separate w1thermsensor package.

Parse the file text

The stand-in parses text in the same format, including a failed checksum, so you can test your parser anywhere.

Python Stand-in: parse a w1_slave reading

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

DHT22

The DHT22 has four pins (one unused) and its own timing protocol that the Pi must follow within microseconds, which is why it needs a special library (read-only):

Python
import adafruit_dht
import board

sensor = adafruit_dht.DHT22(board.D4)
try:
    print(sensor.temperature, sensor.humidity)
except RuntimeError as error:
    print("retry:", error)        # misreads are normal

Because Linux is not a real-time system, the DHT22 misreads fairly often. Good code wraps every read in try/except and just tries again two seconds later. Never read it more often than every 2 seconds. A 10 kilohm pull-up between data and power is usually required.

BME280 on I2C

The BME280 is accurate and also reports air pressure, which makes it a mini weather station. Connect VCC to 3.3 V, GND, SDA to pin 3 and SCL to pin 5. i2cdetect -y 1 should show it at address 0x76 or 0x77. Read it with a library (read-only):

Python
import board
import adafruit_bme280.basic as adafruit_bme280

i2c = board.I2C()
bme = adafruit_bme280.Adafruit_BME280_I2C(i2c, address=0x76)
print(bme.temperature, bme.relative_humidity, bme.pressure)

Making readings reliable

Raw readings are noisy: a single sample can jump by half a degree or return an outlier. Three habits fix most problems:

  1. Average several samples (or take the median).
  2. Reject impossible values (a room at 400 degrees is a glitch).
  3. Log with a timestamp so you can chart the data later.
Python Stand-in: filter and average readings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The DS18B20 returns exactly 85.0 when it has just powered on without taking a measurement, and -127 when the line is disconnected, so both are rejected.

Log to a file

A small logging loop writes one line per reading. The stand-in generates the CSV text in memory so you can see the format; the real version would open a file in append mode and sleep(60) between rows.

Python Stand-in: CSV logger

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Placement tips

Do not put the sensor next to the Pi's processor: the board runs warm and will bias the readings by several degrees. Use a cable of a meter or less and keep the sensor away from sunlight and drafts. For outdoor use, put the sensor in a ventilated shield, not a sealed box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What extra part does the DS18B20 need between its data line and 3.3 V?

    The 1-Wire bus needs a pull-up resistor to idle high.
  2. 2. Why wrap DHT22 reads in try/except?

    Linux timing jitter causes occasional failed reads.
  3. 3. Which sensor also reports air pressure?

    The BME280 reports temperature, humidity and pressure.
  4. 4. Why average several samples?

    Averaging or taking the median smooths random fluctuations.

Summary

  • DS18B20 uses 1-Wire and a 4.7 kilohm pull-up; the kernel exposes it as a file.
  • DHT22 gives humidity too but is slow and needs retries; BME280 on I2C adds pressure.
  • Filter impossible values, average, and log with timestamps.
  • Keep the sensor away from the Pi's heat.

Next: Distance and Motion Sensors