Ro Led
/
Nucleo_DHT11_Example
Simple example to read humidity and temperature from DHT11 sensor
Diff: DHT11.h
- Revision:
- 0:dbffab632178
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/DHT11.h Wed Apr 05 14:04:25 2017 +0000 @@ -0,0 +1,85 @@ +#include "mbed.h" + +//Class to manage DHT11 sensor +class DHT11{ + + public: + /* Takes the data pin of the sensor in parameter */ + DHT11(PinName pin):dataPin(pin) + { + iBit = 0; + data = 0; + } + + /* Request and receive new data from sensor + Returns : + 1 : OK + -1 : Checksum Error + */ + int readData(void){ + this->data = 0; + this->dataPin.output(); + // Request a measurement (low during t > 18ms) + this->dataPin = 0; + wait_ms(20); + this->dataPin = 1; + + //Wait for the sensor to take control and set low level /!\ Important + wait_us(20); + + this->dataPin.input(); + + //TODO Check if timing is correct (low : 80µs ; high 80µs) + // Wait until end of 80µs low + while(!this->dataPin.read()); + // Wait until end of 80 µs high + while(this->dataPin.read()); + + // Sensor reply 40bits + for(iBit=0; iBit<40; iBit++) { + this->data = this->data << 1; // Shift for new number + this->timer.stop(); + this->timer.reset(); + + // Wait for low level to end + while(!this->dataPin.read()); + this->timer.start(); + // Count time while high level + while(this->dataPin.read()); + + if(this->timer.read_us() > 50) + { + //This bit is '1' + this->data++; + } + } + + wait_ms(250); + + //Checking checksum + if((this->data & 0x00000000000000ff) != ((this->data & 0x000000ff00000000) >> 32) + + ((this->data & 0x00000000ff000000) >> 24) + + ((this->data & 0x0000000000ff0000) >> 16) + + ((this->data & 0x000000000000ff00) >> 8)) + { + return -1; + } + + return 1; + } + + int getTemperature(void){ + return (int)((this->data & 0x0000000000ff0000) >> 16); + } + + int getHumidity(void){ + return (int)((this->data & 0x000000ff00000000) >> 32); + } + + + private: + DigitalInOut dataPin;//Communication with the sensor + Timer timer; //initialize timer + uint64_t data; // 64 bit variable for temporary data + int iBit; +};