electronut Programming & Embedded Systems - by Mahesh Venkitachalam

Talking to DHT11 Humidity & Temperature Sensor

I am working on a "weather monitor" project that involves a Raspberry Pi taking to a DHT11 Humidity and Temperature sensor and serving up the collected data as a graph, over a web page. So, I wanted to first get an idea about how this sensor works.

The DHT11 is designed to work with a microcontroller, but we can coax it to send data with a simple circuit, as shown above.

The DHT11 data sheet says that if we pull the input line LOW for 18 ms, pull the line HIGH and wait for 20-40 us, the DHT11 should start transmitting data. Pulling the line LOW can be done by just pressing the button. Here's the oscilloscope output right after I press the push button.

Just like the data sheet said, 80 us LOW, 80 us HIGH, followed by 40 bits of data. The HIGH bits are 70 us long, and the LOW bits are 26-28 us long. Writing this bit stream out on a piece of paper, I got:

00110111 00000000 00011010 00000000 01010001

Let's decode this with a bit of Python:

>>> x = '00110111 00000000 00011010 00000000 01010001'.split()
>>> x
['00110111', '00000000', '00011010', '00000000', '01010001']
>>> [int(i, 2) for i in x]
[55, 0, 26, 0, 81]

The first two numbers represent the Relative Humidity % (55.0), the next two the temperature n Centigrade (26.0), and the last number is a checksum (81 == 55 + 26). Looks good!

I tried to write some Python code to read the data, but unfortunately, my Python data loop does not seem fast enough to get the 40 bits without errors. Since I am on a deadline, I ended up using Adafruit's DHT driver below, which uses memory-mapped I/O. I need to study their code. ;-)


If you liked this article, please consider supporting my efforts by purchasing my book.

Python Playground, published by No Starch Press, USA, is a collection of imaginative programming projects that will inspire you to use Python to make art and music, build simulations of real-world phenomena, and interact with hardware like the Arduino and Raspberry Pi. Do check it out!