Raspberry Pi Temperature and Humidity Sensor: DHT11 With Python and C++

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 NameAmazon.comAliExpress
1Raspberry Pi 5 (4GB or 8GB)AmazonAliExpress
1Raspberry Pi 27W USB-C Power SupplyAmazonAliExpress
1DHT11 Temperature and Humidity Sensor ModuleAmazonAliExpress
1BreadboardAmazonAliExpress
1Jumper WiresAmazonAliExpress

#1

Wire the DHT11 (3 wires)

Raspberry Pi DHT11 wiring diagram: DHT11 module + to 3.3V pin 1, out to GPIO4 pin 7, and − to GND pin 6 on a Raspberry Pi 5

DHT11 Module Raspberry Pi 5 + (VCC) 3.3V (pin 1) out (DATA) GPIO4 (pin 7) − (GND) GND (pin 6)

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

Raspberry Pi 5 dtoverlay dht11 gpiopin=4 loads the kernel DHT11 driver without a reboot and creates /sys/bus/iio/devices/iio:device0 named dht11@4
Raspberry Pi 5 dtoverlay dht11 gpiopin=4 loads the kernel DHT11 driver without a reboot and creates /sys/bus/iio/devices/iio:device0 named dht11@4

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

Raspberry Pi DHT11 cat in_temp_input returns 24100 (24.1 °C) and in_humidityrelative_input returns 51000 (51 %RH)
Raspberry Pi DHT11 cat in_temp_input returns 24100 (24.1 °C) and in_humidityrelative_input returns 51000 (51 %RH)

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)

Raspberry Pi DHT11 Python script printing temperature and humidity every 2 seconds
Raspberry Pi DHT11 Python script printing temperature and humidity every 2 seconds

#5

Run the C++ program

C++ Code (dht11_read.cpp)

Raspberry Pi DHT11 C++ program reading the kernel driver files and printing temperature and humidity
Raspberry Pi DHT11 C++ program reading the kernel driver files and printing temperature and humidity

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

Raspberry Pi DHT11 end result: the same temperature and humidity from the Python and C++ programs
Raspberry Pi DHT11 end result: the same temperature and humidity from the Python and C++ programs

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:

ParameterDHT11
Supply3.3V to 5.5V
Humidity range and accuracy20–90 %RH, ±5 %RH (at 25°C)
Temperature range and accuracy0–50°C, ±2°C
Resolution1 %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
Current0.3mA measuring, 60µA standby
InterfaceSingle-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

DHT11DHT22 (AM2302)
Humidity20–90 %RH, ±5 %RH0–100 %RH, ±2 %RH (±5 max)
Temperature0–50°C, ±2°C−40 to 80°C, ±0.5°C
Resolution1 %RH, 1°C (0.1°C on newer parts)0.1 %RH, 0.1°C
Sampling interval1–2 s2 s
Supply3.3–5.5V3.3–6V
Start signal from the host≥ 18 ms low≥ 1 ms low
Linux driverdtoverlay=dht11the 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

DHT11 pinout: 3-pin module with + (VCC), out (DATA) and − (GND), and the bare 4-pin DHT11 with VCC, DATA, NC and GND

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.

DHT11 single-wire timing: 18 ms start signal from the Raspberry Pi, 80 µs response low and high, then data bits with 26-28 µs high for 0 and 70 µs high for 1

Raspberry Pi 5 DHT11 oscilloscope capture: 19.84 ms start signal from the kernel driver followed by the 3.74 ms data frame
Raspberry Pi 5 DHT11 oscilloscope capture: 19.84 ms start signal from the kernel driver followed by the 3.74 ms data frame

Raspberry Pi DHT11 40-bit data frame on the oscilloscope: 53 µs lows, 24 µs highs for 0 and 70 µs highs for 1
Raspberry Pi DHT11 40-bit data frame on the oscilloscope: 53 µs lows, 24 µs highs for 0 and 70 µs highs for 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:

DHT11 40-bit data frame decoded from a Raspberry Pi 5 capture: 0x34 0x00 0x18 0x08 with checksum 0x54, 52 %RH and 24.8 °C

Measured on my Pi 5DatasheetScope
Start signal (low)≥ 18 ms19.84 ms
Release to response20–40µs9.9µs
Response low / high80 / 80µs82.2 / 86.1µs
Bit low50µs53.3µs
0 bit high26–28µs23.2–24.9µs
1 bit high70µs70.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:

Raspberry Pi 5 DHT11 success rate by reading method: kernel dht11 driver, libgpiod edge events in C++ and Python, adafruit-circuitpython-dht with pulseio and bit-banging

MethodGood readsRead time (median)CPU per readErrors seen
Kernel dht11 driver (Python)500/500 (100%)24 ms0.17 msnone
Kernel dht11 driver (C++)100/100 (100%)24 ms0.08 msnone
libgpiod edge events (C++)311/311 (100%)28 ms0.45 msnone
libgpiod edge events (Python)50/50 (100%)28 ms1.45 msnone
adafruit-circuitpython-dht (pulseio)500/500 (100%)251 ms0.76 ms + helper processnone
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:

FileMeaning
/sys/bus/iio/devices/iio:device0/in_temp_inputTemperature in m°C (24800 = 24.8°C)
…/in_humidityrelative_inputHumidity in m%RH (52000 = 52 %RH)
…/namedht11@4 (the number is the GPIO)
/sys/class/hwmon/hwmonN/temp1_inputThe 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):

Python Code (dht11_adafruit.py)

Raspberry Pi 5 adafruit-circuitpython-dht installed in a venv and reading the DHT11 temperature and humidity
Raspberry Pi 5 adafruit-circuitpython-dht installed in a venv and reading the DHT11 temperature and humidity

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):

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:

Raspberry Pi 5 pip install Adafruit_DHT fails: Could not detect if running on the Raspberry Pi or Beaglebone Black
Raspberry Pi 5 pip install Adafruit_DHT fails: Could not detect if running on the Raspberry Pi or Beaglebone Black

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)

C++ Code (dht11_robust.cpp)

Raspberry Pi DHT11 robust reading in Python and C++ with retry, range check and a 5-sample median
Raspberry Pi DHT11 robust reading in Python and C++ with retry, range check and a 5-sample median


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)

Raspberry Pi DHT11 temperature and humidity logger service active (running) and the first CSV rows
Raspberry Pi DHT11 temperature and humidity logger service active (running) and the first CSV rows

Raspberry Pi DHT11 temperature and humidity log chart rendered from the logger's CSV file

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

Raspberry Pi ls /sys/bus/iio/devices shows no iio:device0 because the dht11 overlay isn't loaded
Raspberry Pi ls /sys/bus/iio/devices shows no iio:device0 because the dht11 overlay isn’t loaded

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

Raspberry Pi DHT11 cat in_temp_input: Connection timed out, dmesg Only 0 signal edges detected, caused by the wrong gpiopin
Raspberry Pi DHT11 cat in_temp_input: Connection timed out, dmesg Only 0 signal edges detected, caused by the wrong gpiopin

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 pip install adafruit-circuitpython-dht: error externally-managed-environment
Raspberry Pi pip install adafruit-circuitpython-dht: error 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.

Share This Page With Your Network!
Join Our +25,000 Newsletter Subscribers!

Stay Updated With All New Content Releases. You Also Get Occasional FREE Coupon Codes For Courses & Other Stuff!

Photo of author
Author
Embedded systems engineer with several years of experience in embedded software and hardware design. I work as an embedded SW engineer in the Automotive & e-Mobility industry. However, I still do Hardware design and SW development for DSP, Control Systems, Robotics, AI/ML, and other fields I'm passionate about.
I love reading, writing, creating projects, and teaching. A reader by day and a writer by night, it's my lifestyle. I believe that the combination of brilliant minds, bold ideas, and a complete disregard for what is possible, can and will change the world! I will be there when it happens, will you?

Leave a Comment