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.

Revision:
13:11d0770eb603
Parent:
12:af1eadec17e5
--- a/DHT11.h	Mon May 31 07:02:00 2021 +0000
+++ b/DHT11.h	Wed Sep 15 14:47:06 2021 +0000
@@ -29,14 +29,7 @@
  *
  * 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());
- *     }
+ *     printf("T:%d, H:%d\r\n", d.readTemperature(), d.readHumidity());
  * }
  * @endcode
  */
@@ -50,7 +43,8 @@
     DHT11(PinName pin);
     ~DHT11();
 
-    /** Reading the data from the DHT11
+    /** Reading the data from the DHT11.  Calling this is not required, but
+     * may be useful for debug.
      * @return Error code
      *     0: OK.
      *     1: Reading the data too often.
@@ -62,15 +56,17 @@
      */
     int readData(void);
 
-    /** Reading the humidity from the data
-     * @return Humidity in %,
-     * regardless of the error from readData()
+    /** Returns the current humidity from the DHT11.  If the existing data record
+     * is older than 2000ms, initiates a read from the device.  Note that errors
+     * may result in infinite attempts to read.
+     * @return Humidity in %
      */
     int readHumidity(void);
 
-    /** Reading the temperature from the data
-     * @return Temperature in Celcius,
-     * regardless of the error from readData()
+    /** Returns the current temperature from the DHT11.  If the existing data record
+     * is older than 2000ms, initiates a read from the device.  Note that errors
+     * may result in infinite attempts to read.
+     * @return Temperature in Celcius
      */
     int readTemperature(void);
 
@@ -91,7 +87,6 @@
     uint32_t t_pulse_us;
     const static int t_tol_start;    
     const static int t_tol_pulse;
-    bool first_time;
     uint64_t data;
     uint32_t chksum;
     uint32_t cnt;
@@ -100,6 +95,7 @@
     void init(void);
     void pos_edge(void);
     void neg_edge(void);
+    void readNewData(void);
 };
 
 #endif
\ No newline at end of file