From 6ff78f802d3c8b14c225786625770887c0011c81 Mon Sep 17 00:00:00 2001 From: sheinz Date: Wed, 6 Jul 2016 21:01:44 +0300 Subject: [PATCH] DHT11/DHT22 library fixes. Fixed temperature below zero. Fixed checksum overflow verification. Fixed inconsistent reading of DHT11. --- examples/dht_sensor/dht_sensor.c | 8 ++++---- extras/dht/dht.c | 7 ++++--- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/examples/dht_sensor/dht_sensor.c b/examples/dht_sensor/dht_sensor.c index 46292da..425d5c0 100644 --- a/examples/dht_sensor/dht_sensor.c +++ b/examples/dht_sensor/dht_sensor.c @@ -15,7 +15,7 @@ * to read and print a new temperature and humidity measurement * from a sensor attached to GPIO pin 4. */ -uint8_t const dht_gpio = 12; +uint8_t const dht_gpio = 4; void dhtMeasurementTask(void *pvParameters) { @@ -29,9 +29,9 @@ void dhtMeasurementTask(void *pvParameters) while(1) { if (dht_read_data(dht_gpio, &humidity, &temperature)) { - printf("Humidity: %d.%d%% Temp: %d.%dC\n", - humidity / 10, humidity % 10, - temperature / 10, abs(temperature) % 10); + printf("Humidity: %d%% Temp: %dC\n", + humidity / 10, + temperature / 10); } else { printf("Could not read data from sensor\n"); } diff --git a/extras/dht/dht.c b/extras/dht/dht.c index cd84eba..3930735 100644 --- a/extras/dht/dht.c +++ b/extras/dht/dht.c @@ -64,13 +64,14 @@ static bool dht_await_pin_state(uint8_t pin, uint32_t timeout, bool expected_pin_state, uint32_t *duration) { for (uint32_t i = 0; i < timeout; i += DHT_TIMER_INTERVAL) { + // need to wait at least a single interval to prevent reading a jitter + sdk_os_delay_us(DHT_TIMER_INTERVAL); if (gpio_read(pin) == expected_pin_state) { if (duration) { *duration = i; } return true; } - sdk_os_delay_us(DHT_TIMER_INTERVAL); } return false; @@ -135,7 +136,7 @@ static inline int16_t dht_convert_data(uint8_t msb, uint8_t lsb) data = msb & 0x7F; data <<= 8; data |= lsb; - if (msb & BIT(15)) { + if (msb & BIT(7)) { data = 0 - data; // convert it to negative } #elif DHT_TYPE == DHT11 @@ -169,7 +170,7 @@ bool dht_read_data(uint8_t pin, int16_t *humidity, int16_t *temperature) data[i/8] |= bits[i]; } - if (data[4] != (data[0] + data[1] + data[2] + data[3])) { + if (data[4] != ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) { debug("Checksum failed, invalid data received from sensor\n"); return false; }