Raspberry Pi reads DHT11 via Arduino

DHT11 is a widely used humidity/temperature sensor. If you try to use DHT11 on Raspberry Pi, you will see it is not easy to achieve a good result. The DHT11 sends out its data with very high speed, the pulse for one bit is just 26us~70us. In order to read all the bits, you may have to keep checking the data pin in a loop with very short interval. As a result, the CPU usage of your Pi will go high when your application talks to DHT11, and all other applications on the Pi will have to compete with yours little application in that period (although it is not long). Please notice that Raspberry Pi is not running a real-time OS, so when others are competing with you for CPU resource, your readings in loop will not be regular and you may miss one or more bits, and then get a checksum verification failure at the end, or a timeout if you miss too much data.

This problem could be solved by using Arduino with Raspberry Pi together, and deploy the UUGear solution on both sides. By using the UUGear solution, your application on Pi can not only access all the pins on Arduino, but also the DHT11 sensor connected to it!

The Wiring

The wiring is very simple, just use USB cable to connect Arduino Nano and Raspberry Pi, wire DHT11’s pins to VCC, D4 and GND on Arduino, and don’t forget the pull up resistor between VCC and DATA pin.

dht11_wiringThe Source Code

You can write your application in C or Python, as UUGear solution provides APIs for both languages. After finding the Arduino device by its unique, constant id, your application can then read DHT11 data directly. Don’t know how to get the Arduino device id? Please read the project homepage.

The readDHT11() function is a blocking function, and it will return in about 26ms. The return value contains the temperature (degree centigrade) on lowest byte and the humidity (percentage) on higher byte.

Here is an example in C:

The same example in Python is below:

Both are very simple :-)

You may noticed that I put one second delay in the loop. It is recommended to do so because DHT11 may not work correctly if you pull data from it too frequently. Experiment shows that querying DHT11 per second is very safe and it will never fail.

Video Demo

Here is a video to demonstrate the result. You can monitor the humidity and temperature in real-time, via an application running on Raspberry Pi!

Conclusion

Using Arduino as an extension of Raspberry Pi can not only get more GPIO pins, but also make good use of those components designed for Arduino. In this example, Raspberry Pi can read humidity and temperature from DHT11 sensor via Arduino, with 100% reliability, and very low CPU usage. The result is quite satisfying.

 

 

See also