Simple library for the DHT11 temperature and humidity sensor. Forked from an existing Mbed DHT11 project.

Dependents:   UoY-DHT11-test

Simple DHT11 temperature and humidity library.

Example usage

#include "mbed.h"
#include "DHT11.h"

DHT11 dht(D8); // Change pin name here if required

main()
{
    printf("T:%d, H:%d\r\n", dht.readTemperature(), dht.readHumidity());
}

The sensor may be read as often as desired, but temperature and humidity values are cached and will only be updated if they are more than 2 seconds old. This is the underlying sensor update rate.

Please note that this project has been modified only enough to make it work for its intended purpose. Various parts of this project still need work, and the source code should not be seen as an example of best practice.

DHT11.h

Committer:
s_inoue_mbed
Date:
2014-09-10
Revision:
4:48798b126d93
Parent:
3:8cd064147bde
Child:
5:da586c935e88

File content as of revision 4:48798b126d93:

/*
 * Library for the use of the DHT11, a temperature and humidity sensor
 * Shigenori Inoue, September 10, 2014
 */
#ifndef __DHT11__
#define __DHT11__
#include "mbed.h"

/**  Example:
 * @code
 * #include "mbed.h"
 * #include "DHT11.h"
 *
 * DHT11 d;
 *
 * main()
 * {
 *     int s;
 *     s = d.readData();
 *     if (s != DHT11::OK) {
 *         printf("Error!\r\n");
 *     }
 *     else {
 *         printf("T:%d, H:%d\r\n", d.readTemperature(), d.readHumidity());
 *     }
 * }
 * @endcode
 */

class DHT11
{
public:
    /** Create a DHT11 interface
     * @param pin 1-wire-like serial I/O port of DHT11
     */
    DHT11(PinName pin);
    ~DHT11();

    /** Reading the data from the DHT11
     * @return Error code
     *     0: OK.
     *     1: Reading the data too often.
     *     2: 1-wire bus is busy.
     *     3: DHT11 does not respond.
     *     4: DHT11 is not ready.
     *     5: Checksum is incorrect.
     *     6: Timeout
     */
    int readData(void);

    /** Reading the humidity from the data
     * @return Humidity in % if readData() returns no error. Otherwise, returns 0xffffffff.
     */
    int readHumidity(void);

    /** Reading the temperature from the data
     * @return Temperature in Celcius if readData() returns no error. Otherwise, returns 0xffffffff.
     */
    int readTemperature(void);

    enum ErrorDHT11 {
        OK = 0,
        TOO_FAST_READ = 1,
        BUS_BUSY = 2,
        NOT_PRESENT = 3,
        NOT_READY = 4,
        CHKSUM_ERR = 5,
        WATCHDOG_ERR = 6,
    };

private:
    PinName _pin;
    DigitalInOut io;
    InterruptIn io_irq;
    Timer t;
    uint32_t t_pulse_us;
    bool first_time;
    uint64_t data;
    uint32_t chksum;
    uint32_t cnt;
    uint32_t wdt;
    bool eod;
    ErrorDHT11 err;
    void init(void);
    void pos_edge(void);
    void neg_edge(void);
};

#endif