From e139aa7e9c3bde453c0de29e0338e464028b791f Mon Sep 17 00:00:00 2001 From: Arthur Roberts Date: Mon, 30 Oct 2023 22:11:39 +0000 Subject: [PATCH] Every 4th byte comes back with zero time elapsed high. Really don't know why --- components/dht22/dht22.c | 27 +++++++++++++++------------ components/dht22/dht22.h | 2 ++ main/main.c | 1 + 3 files changed, 18 insertions(+), 12 deletions(-) diff --git a/components/dht22/dht22.c b/components/dht22/dht22.c index 6ea1130..2130de5 100644 --- a/components/dht22/dht22.c +++ b/components/dht22/dht22.c @@ -24,25 +24,28 @@ void dht22_handle_error(dht22_error e) { ESP_LOGE(TAG, "Error calculating checksum"); } else if (e == DHT22_TIMING_ERROR) { ESP_LOGE(TAG, "Timing error while obtaining data"); + } else if (e == DHT22_TIMEOUT_ERROR) { + ESP_LOGE(TAG, "Timeout error - waited >2ms for signal to change"); + } else { + ESP_LOGE(TAG, "Unknown error: %i", e); } } uint32_t wait_for_signal_to_change_from(int signal_level) { - uint32_t tick_total = 0; uint64_t start_time = esp_timer_get_time(); + uint64_t next_time = start_time; while (gpio_get_level(CONFIG_DHT22_DATA_GPIO) == signal_level) { - tick_total += 1; - // TODO: Find a better way to determine the max timeout - perhaps find number of ticks - // in 50ms or something - // Or perhaps do actually run esp_timer_get_time in the loop or something - if (tick_total == (UINT32_MAX - 1)) { - return DHT22_TIMING_ERROR; + next_time = esp_timer_get_time(); + if ((next_time - start_time) >= 1000 * 10) { + return DHT22_TIMEOUT_ERROR; } } - uint64_t next_time = esp_timer_get_time(); uint32_t elapsed_time = next_time - start_time; + if (elapsed_time == 0) { + return 1000; + } return elapsed_time; } @@ -97,19 +100,19 @@ dht22_error dht22_read() { for (int bit_i = 0; bit_i <= 8; bit_i++) { elapsed_time = wait_for_signal_to_change_from(0); + if (elapsed_time == DHT22_TIMEOUT_ERROR) { + return DHT22_TIMEOUT_ERROR; + } if (elapsed_time < 35 || elapsed_time > 65) { - return DHT22_TIMING_ERROR; + return elapsed_time; } elapsed_time = wait_for_signal_to_change_from(1); - /* if (elapsed_time < 60 || elapsed_time > 80) { data[byte_i] |= (1 << bit_i); } - */ ESP_LOGE(TAG, "elapsed_time: %lu", elapsed_time); } - } // TODO test that data[x] << 8 will be promoted to 16bits otherwise I'm diff --git a/components/dht22/dht22.h b/components/dht22/dht22.h index cf488f3..cf479fc 100644 --- a/components/dht22/dht22.h +++ b/components/dht22/dht22.h @@ -1,9 +1,11 @@ #pragma once +#include #include typedef enum { DHT22_OK, + DHT22_TIMEOUT_ERROR, DHT22_TIMING_ERROR, DHT22_CHECKSUM_ERROR, } dht22_error; diff --git a/main/main.c b/main/main.c index b233b7e..4078799 100644 --- a/main/main.c +++ b/main/main.c @@ -73,6 +73,7 @@ void read_from_dht22() { if (ret != DHT22_OK) { dht22_handle_error(ret); } else { + latest_datapoint.temp = dht22_temperature(); latest_datapoint.rh = dht22_relative_humidity(); ESP_LOGW(TAG, "%f & %f", latest_datapoint.temp / 10.0, latest_datapoint.rh / 10.0 );