Read DHT11/22 Temperature & Humidity Sensor from Raspberry Pi

DHT11 and DHT22 are very frequently used in projects that need to measure environment temperature and humidity.  They have different range of measurement and accuracy.
In order to make DHT11/22 work properly, usually you need to connect a 4.7~10K pull-up resistor between the data pin and the VCC. Our DHT11 and DHT22 modules already have this pull up resistor on board and you can just connect them to your Raspberry Pi directly.


DHT11 Module

Power: DC 3~5V
Pins: G (GND) – V (VCC) – D (Data)
Humidity Measurement: 20~80% humidity reading with 5% accuracy
Temperature Measurement: 0~50°C temperature reading with ±2°C accuracy
Should not measure more than once per second






DHT22 Module

Power: DC 3~5V
Pins: G (GND) – V (VCC) – D (Data)
Humidity Measurement: 0~100% humidity reading with 2~5% accuracy
Temperature Measurement: -40~125°C temperature reading with ±0.5°C accuracy
Should not measure more than once in every two seconds

The Wiring

The wiring is very simple, just connect the G pin to ground (GND), V pin to +3.3V (or 5V), and D pin to the GPIO pin that you choose.
In our example, we choose GPIO-22 (pin 3 in wiringPi’s default numbering).
The figure below shows how a DHT22 module is connected to Raspberry Pi:

Example Source Code

Below is an example that could work with both DHT11 and DHT22 modules. The source code is in C language:

To compile the code, you need to install the wiringPi first, then run:

After the compiling, you will see an executable file named “dht” and you can run it with:

Then it will print the temperature and humidity on the console for every 2 seconds. Sometimes the reading may fail, and you see a message “Data not good, skip” on the console. That’s because reading from DHT11/22 module is quite critical to timing, if the CPU is assigned to execute some other tasks in the background, it may not fit the timing requirement and cause a reading failure. In real application, you should cache the last good data read from the sensor, and return the cached data when reading is failed.
The way to read data from DHT11 and DHT22 is the same, the only different part is how to process the data you read. Pay attention to line 69~72 and line 74~77, they make sure both DHT11 and DHT22 can work with this code.

Python Example?

It should be possible to implement an example with Python language as well. However, using pure Python to read DHT11/22 sensor might not get ideal result, since the CPU has bigger chance to be assigned with other tasks during the reading, and cause very high chance to fail, which make it almost not usable.
A workaround is to implement the reading in C and then wrap it as Python library, or using an Arduino to read the DHT sensor.

See also