52 lines
1.4 KiB
C
52 lines
1.4 KiB
C
#include "dht22.h"
|
|
#include "sdkconfig.h"
|
|
#include "esp_log.h"
|
|
|
|
#define DATA_GPIO CONFIG_DHT22_DATA_GPIO
|
|
|
|
#if DATA_GPIO == -1
|
|
#error "Please define your DHT22 GPIO Data Pin"
|
|
#endif /* CONFIG_DHT22_DATA_GPIO == -1 */
|
|
|
|
static const char* TAG = "DHT22";
|
|
deci_percent _dht22_relative_humidity = UINT16_MAX;
|
|
deci_degrees_c _dht22_temperature = INT16_MIN;
|
|
|
|
void dht22_handle_error(dht22_error e) {
|
|
if (e == DHT22_OK) {
|
|
ESP_LOGI(TAG, "No errors reading DHT22 value");
|
|
} else if (e == DHT22_CHECKSUM_ERROR) {
|
|
ESP_LOGE(TAG, "Error calculating checksum");
|
|
} else if (e == DHT22_TIMING_ERROR) {
|
|
ESP_LOGE(TAG, "Timing error while obtaining data");
|
|
}
|
|
}
|
|
|
|
dht22_error dht22_read() {
|
|
uint8_t data[5] = {0};
|
|
|
|
// TODO: Actually figure out how to read the data from the chip.
|
|
|
|
// TODO test that data[x] << 8 will be promoted to 16bits otherwise I'm shifting them to just zeros
|
|
_dht22_relative_humidity = data[0] << 8 | data[1];
|
|
_dht22_temperature = (data[2] & 0x7f) << 8 | data[3];
|
|
if (data[2] & 0x80) {
|
|
_dht22_temperature = -1 * _dht22_temperature;
|
|
}
|
|
uint8_t checksum_val = (data[0] + data[1] + data[2] + data[3]) & 0xff;
|
|
if (checksum_val != data[4]) {
|
|
_dht22_relative_humidity = UINT16_MAX;
|
|
_dht22_temperature = INT16_MIN;
|
|
return DHT22_CHECKSUM_ERROR;
|
|
}
|
|
|
|
return DHT22_OK;
|
|
}
|
|
|
|
deci_percent dht22_relative_humidity() {
|
|
return _dht22_relative_humidity;
|
|
}
|
|
deci_degrees_c dht22_temperature() {
|
|
return _dht22_temperature;
|
|
}
|