The DHT11 is the cheapest way to add a Raspberry Pi temperature and humidity sensor to a project: three wires, no ADC, and a few lines of code. It also has a reputation for failing randomly on the Raspberry Pi, with RuntimeError messages, None readings, and libraries that no longer install. Is the sensor that unreliable, and what is the dependable way to read it on a Raspberry Pi 5 from Python and C++?
This tutorial starts with a five-step quick start that gives you working readings in a few minutes, using the DHT11 driver built into the Linux kernel. After that, it shows the DHT11 protocol on an oscilloscope, the measured success rate of every reading method over hundreds of reads, how to handle bad readings in code, and a temperature and humidity logger that starts at boot. Without further ado, let’s get right into it!
Note: All steps in this tutorial are tested with: Raspberry Pi 5 (8GB) with Raspberry Pi OS (64-bit) Trixie, and a 3-pin DHT11 module.
This tutorial assumes your Raspberry Pi is set up with Raspberry Pi OS and reachable over SSH. If it isn’t, follow the Raspberry Pi Setup Guide first.
Raspberry Pi DHT11 Quick Start (Python and C++)
You need a Raspberry Pi, a DHT11 module (or the bare sensor plus a 10kΩ resistor), a breadboard, and three jumper wires:
| QTY. | Component Name | Amazon.com | AliExpress |
|---|---|---|---|
| 1 | Raspberry Pi 5 (4GB or 8GB) | Amazon | AliExpress |
| 1 | Raspberry Pi 27W USB-C Power Supply | Amazon | AliExpress |
| 1 | DHT11 Temperature and Humidity Sensor Module | Amazon | AliExpress |
| 1 | Breadboard | Amazon | AliExpress |
| 1 | Jumper Wires | Amazon | AliExpress |
#1
Wire the DHT11 (3 wires)

Connect the module’s + pin to 3.3V, out to GPIO4, and − to GND. The module already has the pull-up resistor; a bare 4-pin DHT11 needs a 4.7kΩ–10kΩ resistor from DATA to 3.3V. Pin numbers are in the Raspberry Pi 5 pinout.
Note: The pin order is not the same on every DHT11 module. Follow the labels printed on your board (+ / VCC, out / S / DATA, − / GND), not the position of the pins.
#2
Load the DHT11 driver
|
1 2 |
sudo dtoverlay dht11 gpiopin=4 echo 'dtoverlay=dht11,gpiopin=4' | sudo tee -a /boot/firmware/config.txt |
The first line loads the kernel dht11 driver right now, without a reboot. The second adds it to /boot/firmware/config.txt so it loads at every boot. Nothing has to be installed: the driver is part of Raspberry Pi OS.
#3
Read the sensor files
|
1 2 |
cat /sys/bus/iio/devices/iio:device0/in_temp_input cat /sys/bus/iio/devices/iio:device0/in_humidityrelative_input |
The values are in thousandths: 24100 = 24.1°C and 51000 = 51 %RH. Any user can read them, so no sudo is needed from here on.
#4
Run the Python script
Python Code (dht11_read.py)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#!/usr/bin/env python3 # Raspberry Pi DHT11: read temperature and humidity through the kernel dht11 driver # (enable it first: sudo dtoverlay dht11 gpiopin=4) import glob, time DEV = next(d for d in glob.glob("/sys/bus/iio/devices/iio:device*") if open(d + "/name").read().startswith("dht11")) def read(channel): with open(f"{DEV}/in_{channel}_input") as f: return int(f.read()) / 1000 # the driver reports milli-units while True: try: print(f"Temperature: {read('temp'):.1f} °C Humidity: {read('humidityrelative'):.0f} %") except OSError as e: # bad frame or no answer: try again next time print("Read failed:", e.strerror) time.sleep(2) # the DHT11 needs 2 s between measurements |
|
1 |
python3 dht11_read.py |
#5
Run the C++ program
C++ Code (dht11_read.cpp)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
// Raspberry Pi DHT11: read temperature and humidity through the kernel dht11 driver // (enable it first: sudo dtoverlay dht11 gpiopin=4) // build: g++ -std=c++17 dht11_read.cpp -o dht11_read #include <cerrno> #include <chrono> #include <cstdio> #include <cstring> #include <fstream> #include <string> #include <thread> const std::string DEV = "/sys/bus/iio/devices/iio:device0/"; // check: cat .../name -> dht11@4 // Returns false on a bad frame (EIO) or a timeout (ETIMEDOUT) bool read_milli(const std::string &file, double &value) { std::ifstream f(DEV + file); long raw; if (!(f >> raw)) return false; value = raw / 1000.0; // milli-units -> °C / %RH return true; } int main() { while (true) { double t, h; if (read_milli("in_temp_input", t) && read_milli("in_humidityrelative_input", h)) std::printf("Temperature: %.1f °C Humidity: %.0f %%\n", t, h); else std::printf("Read failed: %s\n", std::strerror(errno)); std::fflush(stdout); std::this_thread::sleep_for(std::chrono::seconds(2)); // 2 s between measurements } } |
|
1 2 |
g++ -std=c++17 dht11_read.cpp -o dht11_read ./dht11_read |
Neither program needs a library: the kernel driver talks to the sensor, and both just read two files. g++ is on Raspberry Pi OS; if it’s missing, run sudo apt install build-essential.
End Result
Both languages now give working readings. In my tests, this kernel-driver method returned a valid reading 100.0% of the time over 600 reads. The rest of this tutorial explains why that matters, then covers the other reading methods, error handling, a logger, and troubleshooting.
DHT11 Temperature and Humidity Sensor Explained
The DHT11 (Aosong / ASAIR) combines a resistive humidity element, an NTC thermistor, and a small microcontroller that measures both and sends the result as 40 bits over one data wire. The key specs, from the DHT11 datasheet:
| Parameter | DHT11 |
|---|---|
| Supply | 3.3V to 5.5V |
| Humidity range and accuracy | 20–90 %RH, ±5 %RH (at 25°C) |
| Temperature range and accuracy | 0–50°C, ±2°C |
| Resolution | 1 %RH and 1°C (many current parts also send 0.1°C, as mine did) |
| Sampling interval | ≥ 1 s (older sheet) or > 2 s (Aosong manual): use 2 s |
| Current | 0.3mA measuring, 60µA standby |
| Interface | Single-wire, half-duplex (not the Dallas 1-Wire bus) |
Note: A DHT11 answers with the result of its previous measurement (Aosong manual, section 7). After a long pause, the first reading can be minutes old; read twice, 2 s apart, when you need a fresh value.
DHT11 vs DHT22
| DHT11 | DHT22 (AM2302) | |
|---|---|---|
| Humidity | 20–90 %RH, ±5 %RH | 0–100 %RH, ±2 %RH (±5 max) |
| Temperature | 0–50°C, ±2°C | −40 to 80°C, ±0.5°C |
| Resolution | 1 %RH, 1°C (0.1°C on newer parts) | 0.1 %RH, 0.1°C |
| Sampling interval | 1–2 s | 2 s |
| Supply | 3.3–5.5V | 3.3–6V |
| Start signal from the host | ≥ 18 ms low | ≥ 1 ms low |
| Linux driver | dtoverlay=dht11 | the same dtoverlay=dht11 (auto-detected) |
The DHT22 is the better sensor for real measurements; the DHT11 is fine for room monitoring and learning. Both speak the same protocol, so every method in this tutorial reads both. The kernel driver detects which one answered from the data format (dht11.c); with the Adafruit library, use adafruit_dht.DHT22. Specs from the DHT22 datasheet.
DHT11 Pinout

The same sensor on other boards: Arduino DHT11 and Arduino DHT22. For temperature only, with several sensors on one pin, see my Raspberry Pi DS18B20 tutorial.
DHT11 Single-Wire Protocol on the Oscilloscope
The Pi starts every reading by pulling the data line low for at least 18 ms, then releases it. The DHT11 answers with 80µs low and 80µs high, then sends 40 bits. Every bit starts with a 50µs low; the length of the high pulse that follows is the value: about 26–28µs for a 0 and 70µs for a 1.

The 40 bits are five bytes: humidity integer and decimal, temperature integer and decimal, and a checksum, which is the low 8 bits of the sum of the first four. Here is the frame above, decoded:

| Measured on my Pi 5 | Datasheet | Scope |
|---|---|---|
| Start signal (low) | ≥ 18 ms | 19.84 ms |
| Release to response | 20–40µs | 9.9µs |
| Response low / high | 80 / 80µs | 82.2 / 86.1µs |
| Bit low | 50µs | 53.3µs |
| 0 bit high | 26–28µs | 23.2–24.9µs |
| 1 bit high | 70µs | 70.0–70.2µs |
| Whole frame | – | 3.74 ms |
My module answered faster than the datasheet says and sent 0s shorter than 26µs, which is common: decoders compare each high pulse against a threshold between the two lengths instead of an exact value (the kernel driver uses 49µs).
Raspberry Pi DHT11 Reliability: Success Rate by Method (Measured)
A 0 and a 1 differ by about 45µs. A microcontroller times that easily; a Linux program can be paused by the scheduler at any moment, and a pause of a few dozen microseconds in the middle of a frame turns a 0 into a 1 or loses an edge. The checksum then fails, and the library raises an error. The fix is to let the kernel take the timestamps in its GPIO interrupt handler, where a few microseconds of delay don’t change the measured pulse widths.
To put numbers on it, I read the DHT11 on my Pi 5 with every method, 2.2 s between reads, with nothing else running:

| Method | Good reads | Read time (median) | CPU per read | Errors seen |
|---|---|---|---|---|
| Kernel dht11 driver (Python) | 500/500 (100%) | 24 ms | 0.17 ms | none |
| Kernel dht11 driver (C++) | 100/100 (100%) | 24 ms | 0.08 ms | none |
| libgpiod edge events (C++) | 311/311 (100%) | 28 ms | 0.45 ms | none |
| libgpiod edge events (Python) | 50/50 (100%) | 28 ms | 1.45 ms | none |
| adafruit-circuitpython-dht (pulseio) | 500/500 (100%) | 251 ms | 0.76 ms + helper process | none |
| adafruit-circuitpython-dht (bit-bang) | 0/50 (0%) | – (no reading) | 251 ms (busy loop) | DHT sensor not found, check wiring (50) |
Every method that lets the kernel take the timestamps read the DHT11 without a single failure: the kernel driver (600 of 600 reads from Python and C++), libgpiod edge events (361 of 361), and the Adafruit library in its default pulseio mode (500 of 500), which runs Adafruit’s libgpiod_pulsein helper in the background. Pure user-space polling never worked: the same Adafruit library forced to bit-bang (use_pulseio=False) failed all 50 reads with “DHT sensor not found, check wiring”, because a Python loop can’t sample a 26µs pulse, and it burned 251 ms of CPU per attempt.
This is why old Raspberry Pi DHT tutorials talk about random failures. The kernel driver is the one I recommend: it’s built in, it’s the fastest (24 ms per reading), it uses almost no CPU, and it works the same from any language. These runs were on an idle Pi with a short cable; a long cable or a noisy supply will cause occasional checksum errors with any method, so keep the retry logic below.
Raspberry Pi DHT11 Reading Methods Compared
1. Kernel dht11 Driver (Recommended)
The dht11 overlay (overlay README) binds the kernel’s IIO driver to a GPIO. The driver sends the 18–20 ms start signal, timestamps every edge in its interrupt handler, decodes the bits with a 49µs threshold, and checks the checksum (dht11.c). Your program only reads files:
| File | Meaning |
|---|---|
/sys/bus/iio/devices/iio:device0/in_temp_input | Temperature in m°C (24800 = 24.8°C) |
…/in_humidityrelative_input | Humidity in m%RH (52000 = 52 %RH) |
…/name | dht11@4 (the number is the GPIO) |
/sys/class/hwmon/hwmonN/temp1_input | The same values through hwmon (iio_hwmon@4) |
A read that fails returns an error instead of a number: EIO (Input/output error) for a bad checksum or a lost edge, and ETIMEDOUT (Connection timed out) when the sensor doesn’t answer within 1 s. The driver also keeps a good reading for 2 s: reading both files right after each other uses one transaction, and reading faster than every 2 s returns the cached value without touching the sensor.
Tip: To use another pin, change gpiopin. Only one program can own the GPIO: while the overlay is loaded, the Python and C++ libraries below can’t use that pin. sudo dtoverlay -r dht11 unloads it until the next boot.
2. adafruit-circuitpython-dht (Python Library)
Adafruit’s adafruit-circuitpython-dht (version 4.0.12) works on the Pi 5 through Blinka (Adafruit-Blinka 10.4.0). It’s only on PyPI, so install it in a virtual environment; a plain pip install stops with externally-managed-environment (PEP 668):
|
1 2 3 |
sudo dtoverlay -r dht11 # free GPIO4 if the driver is loaded python3 -m venv --system-site-packages ~/dht11/venv ~/dht11/venv/bin/pip install adafruit-circuitpython-dht |
Python Code (dht11_adafruit.py)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#!/usr/bin/env python3 # Raspberry Pi DHT11 with adafruit-circuitpython-dht (run inside the venv) import time import board, adafruit_dht sensor = adafruit_dht.DHT11(board.D4) # GPIO4 = pin 7 (the dht11 overlay must NOT be loaded) try: while True: try: print(f"Temperature: {sensor.temperature:.1f} °C Humidity: {sensor.humidity} %") except RuntimeError as e: # "Checksum did not validate", "A full buffer was not returned"... print("Read failed:", e.args[0]) time.sleep(2) finally: sensor.exit() # stop the libgpiod_pulsein helper process |
The library uses Adafruit’s libgpiod_pulsein helper program on the Pi 5, which records the pulse widths with libgpiod, so it read 500 of 500 frames in my test; each read takes about 251 ms because the library waits a fixed 0.25 s for the pulses. It raises RuntimeError for a bad frame (“Checksum did not validate. Try again.”, “A full buffer was not returned. Try again.”) and returns the previous values when you ask again within 2 s. Don’t pass use_pulseio=False on a Linux board: that pure-Python bit-bang mode failed every read on my Pi 5.
3. libgpiod Edge Events in C++ (No Driver)
Without the overlay, a program can still read the DHT11 reliably if the kernel timestamps the edges: libgpiod v2 delivers every edge as an event with a nanosecond timestamp taken in the interrupt handler, so a delay in your program only delays when you collect the events, not their times. The key part of dht11_gpiod.cpp (full file in the download):
|
1 2 3 4 5 6 7 8 9 |
auto req = chip.prepare_request().set_consumer("dht11") .add_line_settings(4, gpiod::line_settings() .set_direction(gpiod::line::direction::OUTPUT) .set_output_value(gpiod::line::value::INACTIVE)).do_request(); std::this_thread::sleep_for(std::chrono::milliseconds(19)); // start signal req.reconfigure_lines(gpiod::line_config().add_line_settings(4, gpiod::line_settings().set_direction(gpiod::line::direction::INPUT) .set_edge_detection(gpiod::line::edge::BOTH))); // collect edge events for 20 ms, then: high time > 49 us = 1, else 0 |
This decoder read 311 of 311 frames from C++ and 50 of 50 from the same logic in Python (python3-libgpiod), at 28 ms per reading. It’s the option for a GPIO you can’t give to the kernel driver, or for learning how the frame is decoded; for everyday use, the kernel driver does the same job with two file reads. It needs the libgpiod C++ headers: sudo apt install libgpiod-dev.
4. Adafruit_DHT (Deprecated): Doesn’t Install on a Pi 5
Many tutorials still use the old Adafruit_DHT package (Adafruit_Python_DHT, last release 1.4.0 in 2018, archived). On a Raspberry Pi 5 it doesn’t even build:
Its C code reads the old Broadcom GPIO registers, which the Pi 5’s RP1 chip doesn’t have. Use the kernel driver or adafruit-circuitpython-dht instead.
Handling Bad DHT11 Readings (Python and C++)
Even the best method fails now and then (a long cable, a noisy supply), so a program that runs for days needs four rules:
- Respect 2 s between measurements; retrying immediately only reads the same cached value or upsets the sensor.
- Retry with a backoff: 2 s, then 3 s, then 4.5 s, then give up and report the sensor as missing.
- Reject impossible values: the checksum catches most bad frames, a range check catches the rest.
- Median-filter a logger: the median of the last 3–5 readings ignores a single odd value.
Python Code (dht11_robust.py)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
#!/usr/bin/env python3 # Raspberry Pi DHT11: robust reading (retry with backoff, range check, median filter) import glob, statistics, time DEV = next(d for d in glob.glob("/sys/bus/iio/devices/iio:device*") if open(d + "/name").read().startswith("dht11")) MIN_INTERVAL = 2.0 # DHT11: at least 2 s between measurements def read_raw(): with open(f"{DEV}/in_temp_input") as f: t = int(f.read()) / 1000 with open(f"{DEV}/in_humidityrelative_input") as f: h = int(f.read()) / 1000 # same transaction: the driver caches it for 2 s return t, h def read_dht11(retries=3): """One valid (temperature, humidity) pair, or None after `retries` failed attempts.""" delay = MIN_INTERVAL for _ in range(retries): try: t, h = read_raw() if -20 <= t <= 60 and 0 <= h <= 100: # reject impossible values return t, h except OSError: # EIO = checksum/frame error, ETIMEDOUT = no answer pass time.sleep(delay) # never retry faster than the sensor allows delay *= 1.5 # back off a little more each time return None if __name__ == "__main__": temps, hums = [], [] while True: r = read_dht11() if r: temps = (temps + [r[0]])[-5:] # keep the last 5 readings hums = (hums + [r[1]])[-5:] print(f"now {r[0]:.1f} °C {r[1]:.0f} % median-5 {statistics.median(temps):.1f} °C " f"{statistics.median(hums):.0f} %") else: print("sensor not answering, check the wiring") time.sleep(MIN_INTERVAL) |
C++ Code (dht11_robust.cpp)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
// Raspberry Pi DHT11: robust reading (retry with backoff, range check, median filter) // build: g++ -std=c++17 dht11_robust.cpp -o dht11_robust #include <algorithm> #include <chrono> #include <cstdio> #include <deque> #include <fstream> #include <optional> #include <string> #include <thread> const std::string DEV = "/sys/bus/iio/devices/iio:device0/"; const double MIN_INTERVAL = 2.0; // DHT11: at least 2 s between measurements static bool read_milli(const std::string &file, double &v) { std::ifstream f(DEV + file); long raw; if (!(f >> raw)) return false; // EIO (bad frame) or ETIMEDOUT (no answer) v = raw / 1000.0; return true; } struct Reading { double t, h; }; std::optional<Reading> read_dht11(int retries = 3) { double delay = MIN_INTERVAL; for (int i = 0; i < retries; ++i) { Reading r{}; if (read_milli("in_temp_input", r.t) && read_milli("in_humidityrelative_input", r.h) && r.t >= -20 && r.t <= 60 && r.h >= 0 && r.h <= 100) // reject impossible values return r; std::this_thread::sleep_for(std::chrono::duration<double>(delay)); delay *= 1.5; // back off a little more each time } return std::nullopt; } static double median(std::deque<double> d) { std::sort(d.begin(), d.end()); size_t n = d.size(); return n % 2 ? d[n / 2] : (d[n / 2 - 1] + d[n / 2]) / 2.0; } int main() { std::deque<double> temps, hums; while (true) { if (auto r = read_dht11()) { temps.push_back(r->t); hums.push_back(r->h); if (temps.size() > 5) { temps.pop_front(); hums.pop_front(); } // last 5 readings std::printf("now %.1f °C %.0f %% median-5 %.1f °C %.0f %%\n", r->t, r->h, median(temps), median(hums)); } else { std::printf("sensor not answering, check the wiring\n"); } std::fflush(stdout); std::this_thread::sleep_for(std::chrono::duration<double>(MIN_INTERVAL)); } } |
|
1 2 |
g++ -std=c++17 dht11_robust.cpp -o dht11_robust ./dht11_robust |
Raspberry Pi Temperature and Humidity Logger (CSV, systemd)
A logger that writes the median of three readings once a minute to a CSV file and starts at boot. It imports read_dht11() from dht11_robust.py, so keep both files in ~/dht11:
Python Code (dht11_logger.py)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#!/usr/bin/env python3 # Raspberry Pi DHT11 temperature and humidity logger: one CSV row per minute (median of 3 reads) import csv, datetime, statistics, time from pathlib import Path from dht11_robust import read_dht11, MIN_INTERVAL LOG = Path("dht11_log.csv") PERIOD = 60 # seconds between CSV rows while True: start = time.monotonic() reads = [] for _ in range(3): r = read_dht11() if r: reads.append(r) time.sleep(MIN_INTERVAL) new = not LOG.exists() with LOG.open("a", newline="") as f: w = csv.writer(f) if new: w.writerow(["time", "temperature_c", "humidity_pct", "good_reads"]) now = datetime.datetime.now().isoformat(timespec="seconds") if reads: w.writerow([now, statistics.median(r[0] for r in reads), statistics.median(r[1] for r in reads), len(reads)]) else: w.writerow([now, "", "", 0]) # keep the gap visible in the log time.sleep(max(0, PERIOD - (time.monotonic() - start))) |
|
1 2 3 4 5 6 7 8 9 10 11 12 |
[Unit] Description=DHT11 temperature and humidity logger After=multi-user.target [Service] User=pi WorkingDirectory=/home/pi/dht11 ExecStart=/usr/bin/python3 /home/pi/dht11/dht11_logger.py Restart=on-failure [Install] WantedBy=multi-user.target |
|
1 2 |
sudo cp dht11-logger.service /etc/systemd/system/ sudo systemctl enable --now dht11-logger |

The chart is the first 13 minutes of the real log from my desk: 14 rows, all with 3 of 3 good readings, 23.9–24.1°C and 52 %RH. Copy the file to your PC with scp pi@pi5.local:dht11/dht11_log.csv . and open it in any spreadsheet. WorkingDirectory decides where dht11_log.csv is written, and an empty row with 0 good reads marks a minute when the sensor didn’t answer.
Raspberry Pi DHT11 Troubleshooting
No iio:device0 in /sys/bus/iio/devices
The folder is empty (or missing after a fresh boot) when the driver isn’t loaded. Run sudo dtoverlay dht11 gpiopin=4 and check that dtoverlay -l lists it; for every boot, check that dtoverlay=dht11,gpiopin=4 is in /boot/firmware/config.txt (config.txt docs).
cat: Connection timed out
The driver got no answer: dmesg shows Only 0 signal edges detected. Check the gpiopin number (BCM GPIO, not the physical pin), the power wires, and, on a bare sensor, the pull-up resistor; the overlay turns the internal pull-up off ( GPIO_PULL_DISABLE).
cat: Input/output error
A frame arrived but the checksum or an edge was wrong. One now and then is normal: retry after 2 s. Many in a row mean a long or noisy cable, a weak supply, or a missing pull-up; keep the cable under 1 m at 3.3V, as the datasheet asks, or power the sensor from 5V (next tip).
pip: externally-managed-environment
Raspberry Pi OS protects its system Python. Use the venv from method 2; never --break-system-packages or sudo pip.
Readings Repeat or Return None
Both the kernel driver and the Adafruit library return the previous reading when you ask again within 2 s, and the DHT11 itself reports its previous measurement. A loop faster than 2 s sees repeated values (or None in old code), not new data. Slow the loop to 2 s or more.
Powering the DHT11 From 5V
The DHT11 runs from 3.3V to 5.5V, and 5V helps on long cables. But the DATA line is pulled up to the module’s supply, so a module powered from 5V puts 5V on the GPIO, and the Pi’s GPIO isn’t 5V tolerant. On 5V, use a bare sensor with its pull-up to 3.3V, or a level shifter on DATA. My tests here all ran at 3.3V.
Raspberry Pi DHT11 FAQ
How do I use a DHT11 with a Raspberry Pi?
Wire VCC to 3.3V, DATA to GPIO4, and GND to GND, load the driver with sudo dtoverlay dht11 gpiopin=4, and read in_temp_input and in_humidityrelative_input under /sys/bus/iio/devices/iio:device0/. See the quick start.
Are the DHT11 and DHT22 the same?
They use the same pinout and protocol, but the DHT22 (AM2302) is more accurate (±0.5°C, ±2 %RH) and covers a wider range (−40 to 80°C, 0–100 %RH). The kernel driver and the code here read both.
What library should I install for the DHT11?
On a Raspberry Pi 5, none: the kernel dht11 driver is the most reliable option in my tests. If you prefer a Python library, use adafruit-circuitpython-dht in a venv. The old Adafruit_DHT package doesn’t install on a Pi 5.
Does the DHT11 work with the Raspberry Pi 5?
Yes. Everything in this tutorial was tested on a Pi 5; the dht11 overlay loads live with dtoverlay, and the C++ and Python code is the same as on older models.
Download Raspberry Pi DHT11 Examples
The download has every Python and C++ example, the libgpiod decoder, the logger and its service file, the success-rate benchmark, and a README with the build and run commands.
Download Raspberry Pi DHT11 Examples (Python, C++)
Download all attachment files for this Article/Tutorial (project files, schematics, code, etc.) using the link below. Everything is tested and verified to work on real hardware, as you’ve seen in the demo videos & screenshots. Please consider supporting my work if it helped you.
Wrap Up
To conclude this tutorial, we’ve wired a DHT11 to the Raspberry Pi 5, loaded the kernel driver, and read the temperature and humidity from the command line, Python, and C++, with error handling and a logger that starts at boot. The success-rate runs answer the question from the introduction: the DHT11 itself is fine, and failures come from timing it in user space. With the kernel driver, every one of 600 reads was good, in 24 ms each.
For temperature only, with several sensors on one pin, see the Raspberry Pi DS18B20 tutorial. The GPIO basics are in the Raspberry Pi GPIO tutorial, the user-space timing limits in the GPIO library comparison, and all the Raspberry Pi tutorials are listed on the Raspberry Pi tutorials page.