DHT11/22 Hygrometer Unit

This is a new library unit for reading either the DHT11 or DHT22 relative humidity sensors. Such a device is also known as a hygrometer.

For reference, the identical pinouts of the DHT11 and  DHT22 are, looking from the front, (grill side):

Pin 1: +5V
Pin 2: the data pin
Pin 3: no connection
Pin 4: ground

These sensors transmit data via pulse code modulation at a  fairly zippy rate, so the microcontroller clock should be  at least 8 MHz. Observe that the DHT11 should not be polled  more frequently than once a second and the DHT22 more than  once every two seconds.


This library unit will let you easily exploit the DHT11 or DHT22 relative humidity/temperature sensors in your own programs. The sensors share the same pinouts and obey a similar data transmission protocol. The main differences are in the range, accuracy and decimal representation. In particular, quoting from the spec sheets:

DHT11: senses to the nearest whole number
RH:        20% to 90%,   +/- 5%
Temp (C):  0° to 50°,    +/- 2°
Temp (F):  32° to 122°,  +/- 3.6°

DHT22: senses to the nearest tenth
RH:        0% to 100%,   +/- 2% (5% worst case)
Temp (C):  -40° to 125°, +/- 0.1°
Temp (F):  -40° to 176°, +/- 3.3°

Conditional compilation is employed. The value of DHT_TYPE  determines what code is compiled.  (See below).

There is no need to set or clear the TRIS bit in your  program; it is dealt with automatically.

Compilation Constants

Three conditional compilation constants are required in the main calling program. The first sets the device type, e.g.,




The other constants determine the single data pin, e.g.:


Note that whichever pin is employed for these, it must be capable of both input and output operation and must have a 10k pull-up resistor.


There is one procedure:

readDHT(DHT_rh, DHT_cels, DHT_fahr, DHT_error)

The values returned are, respectively, the relative humidity, temperature in Celsius, temperature in Fahrenheit, and an error indicator.

The humidity and temperatures are signed integers, the error indicator a byte. For the DHT11, the numerical results are simply whole numbers. For the DHT22 numerical results are fixed pointed numbers, with the decimal point assumed one digit from the right. In other words, the values are scaled up by 10. For example, a return value of 657 for the relative humidity would be interpreted as 65.7%.

Also returned for either sensor is an error condition (a byte):

0 = no error
1 = no response from the sensor
2 = bad checksum from the sensor

Add It to Your Library Collection

And here's the new library unit, "DHT11_22.pas" for you to download:

Be sure to read over the source code for additional details on how to use it.

Try It Out

If you'd like to see it in operation, then head over to the exercises to try out the humidity sensor project. Click here to go to it.

No comments:

Post a Comment