-
DHT22:
- 温度范围:-40-80°C
- 温度精度:±0.5°C
- 湿度范围:0-100%RH
- 湿度精度:±2-5%RH
- 分辨率:0.1°C / 0.1%RH
-
#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE#include <stdio.h> #include <freertos/FreeRTOS.h> #include <freertos/task.h> #include "esp_system.h" #include "freertos/event_groups.h"#include "esp_event.h" #include "nvs_flash.h"#include "esp_log.h" #include "driver/gpio.h"#include "DHT.h"// == global defines =============================================static const char *TAG = "DHT";int DHTgpio = GPIO_NUM_4; // my default DHT pin = 4 float humidity = 0.; float temperature = 0.;//串口打印的主函数(默认的波特率为115200) void DHT_task(void *pvParameter) {setDHTgpio(GPIO_NUM_4);ESP_LOGI(TAG, "Starting DHT Task\n\n");while (1){ESP_LOGI(TAG, "=== Reading DHT ===\n");int ret = readDHT();errorHandler(ret);ESP_LOGI(TAG, "Hum: %.1f Tmp: %.1f\n", getHumidity(), getTemperature());// -- wait at least 2 sec before reading again ------------// The interval of whole process must be beyond 2 seconds !!vTaskDelay(2000 / portTICK_PERIOD_MS);} }void app_main() {// Initialize NVSesp_err_t ret = nvs_flash_init();if (ret == ESP_ERR_NVS_NO_FREE_PAGES){ESP_ERROR_CHECK(nvs_flash_erase());ret = nvs_flash_init();}ESP_ERROR_CHECK(ret);esp_log_level_set("*", ESP_LOG_INFO);esp_rom_gpio_pad_select_gpio(GPIO_NUM_4);xTaskCreate(&DHT_task, "DHT_task", 2048, NULL, 5, NULL); }// == set the DHT used pin=========================================void setDHTgpio(int gpio) {DHTgpio = gpio; }// == get temp & hum =============================================float getHumidity() { return humidity; } float getTemperature() { return temperature; }// == error handler ===============================================void errorHandler(int response) {switch (response){case DHT_TIMEOUT_ERROR:ESP_LOGE(TAG, "Sensor Timeout\n");break;case DHT_CHECKSUM_ERROR:ESP_LOGE(TAG, "CheckSum error\n");break;case DHT_OK:break;default:ESP_LOGE(TAG, "Unknown error\n");} }/*------------------------------------------------------------------------------- ; ; get next state ; ; I don't like this logic. It needs some interrupt blocking / priority ; to ensure it runs in realtime. ; ;--------------------------------------------------------------------------------*/int getSignalLevel(int usTimeOut, bool state) {int uSec = 0;while (gpio_get_level(DHTgpio) == state){if (uSec > usTimeOut)return -1;++uSec;esp_rom_delay_us(1); // uSec delay}return uSec; }#define MAXdhtData 5 // to complete 40 = 5*8 Bitsint readDHT() {int uSec = 0;uint8_t dhtData[MAXdhtData];uint8_t byteInx = 0;uint8_t bitInx = 7;for (int k = 0; k < MAXdhtData; k++)dhtData[k] = 0;// == Send start signal to DHT sensor ===========gpio_set_direction(DHTgpio, GPIO_MODE_OUTPUT);// pull down for 3 ms for a smooth and nice wake upgpio_set_level(DHTgpio, 0);esp_rom_delay_us(3000);// pull up for 25 us for a gentile asking for datagpio_set_level(DHTgpio, 1);esp_rom_delay_us(25);gpio_set_direction(DHTgpio, GPIO_MODE_INPUT); // change to input mode// == DHT will keep the line low for 80 us and then high for 80us ====uSec = getSignalLevel(85, 0);// ESP_LOGI(TAG, "Response = %d", uSec);if (uSec < 0)return DHT_TIMEOUT_ERROR;// -- 80us up ------------------------uSec = getSignalLevel(85, 1);// ESP_LOGI(TAG, "Response = %d", uSec);if (uSec < 0)return DHT_TIMEOUT_ERROR;// == No errors, read the 40 data bits ================for (int k = 0; k < 40; k++){// -- starts new data transmission with >50us low signaluSec = getSignalLevel(56, 0);if (uSec < 0)return DHT_TIMEOUT_ERROR;// -- check to see if after >70us rx data is a 0 or a 1uSec = getSignalLevel(75, 1);if (uSec < 0)return DHT_TIMEOUT_ERROR;// add the current read to the output data// since all dhtData array where set to 0 at the start,// only look for "1" (>28us us)if (uSec > 40){dhtData[byteInx] |= (1 << bitInx);}// index to next byteif (bitInx == 0){bitInx = 7;++byteInx;}elsebitInx--;}// == get humidity from Data[0] and Data[1] ==========================humidity = dhtData[0];humidity *= 0x100; // >> 8humidity += dhtData[1];humidity /= 10; // get the decimal// == get temp from Data[2] and Data[3]temperature = dhtData[2] & 0x7F;temperature *= 0x100; // >> 8temperature += dhtData[3];temperature /= 10;if (dhtData[2] & 0x80) // negative temp, brrr it's freezingtemperature *= -1;// == verify if checksum is ok ===========================================// Checksum is the sum of Data 8 bits masked out 0xFFif (dhtData[4] == ((dhtData[0] + dhtData[1] + dhtData[2] + dhtData[3]) & 0xFF))return DHT_OK;elsereturn DHT_CHECKSUM_ERROR; }
DHT.h//对应需要添加头文件
-
/* DHT22 temperature sensor driver相关宏定义和函数的说明 */#ifndef DHT_H_ #define DHT_H_#define DHT_OK 0 #define DHT_CHECKSUM_ERROR -1 #define DHT_TIMEOUT_ERROR -2// == function prototypes =======================================void setDHTgpio(int gpio); void errorHandler(int response); int readDHT(); float getHumidity(); float getTemperature(); int getSignalLevel(int usTimeOut, bool state);#endif
运行结果显示: