#include <driver/rmt.h>
#include <soc/rmt_reg.h>
int temp = 0,hum = 0;
#define DHT11_GPIO 33
int temp_x10 = 123;
int humidity = 60;
const int channel = 0;
uint8_t DHT11_PIN = -1;
static int parse_items(rmt_item32_t *item, int item_num, int *humidity, int *temp_x10);
void DHT11_Init(uint8_t dht11_pin)
{
DHT11_PIN = dht11_pin;
const int RMT_CLK_DIV = 80;
const int RMT_TICK_10_US = (80000000 / RMT_CLK_DIV / 100000);
const int rmt_item32_tIMEOUT_US = 1000;
rmt_config_t rmt_rx = {
.gpio_num = dht11_pin,
.channel = channel,
.clk_div = RMT_CLK_DIV,
.mem_block_num = 1,
.rmt_mode = RMT_MODE_RX,
.rx_config.filter_en = false,
.rx_config.filter_ticks_thresh = 100,
.rx_config.idle_threshold = rmt_item32_tIMEOUT_US / 10 * (RMT_TICK_10_US),
};
rmt_config(&rmt_rx);
rmt_driver_install(rmt_rx.channel, 1000, 0);
}
static int parse_items(rmt_item32_t *item, int item_num, int *humidity, int *temp_x10)
{
int i = 0;
unsigned rh = 0, temp = 0, checksum = 0;
if (item_num < 42){
ESP_LOGI(TAG, "item_num < 42 %d",item_num);
return 0;
}
item++;
for (i = 0; i < 16; i++, item++){
rh = (rh << 1) + (item->duration1 < 35 ? 0 : 1);
}
for (i = 0; i < 16; i++, item++){
temp = (temp << 1) + (item->duration1 < 35 ? 0 : 1);
}
for (i = 0; i < 8; i++, item++){
checksum = (checksum << 1) + (item->duration1 < 35 ? 0 : 1);
}
if ((((temp >> 8) + temp + (rh >> 8) + rh) & 0xFF) != checksum){
ESP_LOGI(TAG, "Checksum failure %4X %4X %2X\n", temp, rh, checksum);
return 0;
}
*humidity = rh >> 8;
*temp_x10 = (temp >> 8) * 10 + (temp & 0xFF);
return 1;
}
int DHT11_StartGet(int *temp_x10, int *humidity)
{
RingbufHandle_t rb = NULL;
size_t rx_size = 0;
rmt_item32_t *item;
int rtn = 0;
rmt_get_ringbuf_handle(channel, &rb);
if (!rb){
return 0;
}
gpio_pad_select_gpio(DHT11_PIN);
gpio_set_direction(DHT11_PIN, GPIO_MODE_OUTPUT);
gpio_set_level(DHT11_PIN, 1);
vTaskDelay(10 / portTICK_PERIOD_MS);
gpio_set_level(DHT11_PIN, 0);
vTaskDelay(25 / portTICK_PERIOD_MS);
rmt_rx_start(channel, 1);
rmt_rx_stop(channel);
gpio_set_direction(DHT11_PIN, GPIO_MODE_INPUT);
rmt_rx_start(channel, 1);
item = (rmt_item32_t *)xRingbufferReceive(rb, &rx_size, 1000 / portTICK_RATE_MS);
if (item != NULL){
int n;
n = rx_size / 4 - 0;
rtn = parse_items(item, n, humidity, temp_x10);
vRingbufferReturnItem(rb, (void *)item);
}
rmt_rx_stop(channel);
return rtn;
}