Browse Source

prueba antes del cambio a componente

dacowars 1 tháng trước cách đây
mục cha
commit
12e2bb4187

+ 1 - 1
.vscode/settings.json

@@ -3,7 +3,7 @@
   "idf.openOcdConfigs": [
     "board/esp32-wrover-kit-3.3v.cfg"
   ],
-  "idf.port": "/dev/tty.usbserial-110",
+  "idf.port": "/dev/tty.usbserial-10",
   "idf.currentSetup": "/Users/daniel/.espressif/v5.5.3/esp-idf",
   "idf.customExtraVars": {
     "IDF_TARGET": "esp32"

+ 3 - 0
components/dht22/CMakeLists.txt

@@ -0,0 +1,3 @@
+idf_component_register(SRCS "dht22.c"
+                    INCLUDE_DIRS "include"
+                    REQUIRES driver)

+ 13 - 0
components/dht22/Kconfig

@@ -0,0 +1,13 @@
+menu "DHT22 configuration"
+
+    orsource "$IDF_PATH/examples/common_components/env_caps/$IDF_TARGET/Kconfig.env_caps"
+
+    config DHT_PIN
+        int "DHT pin configuration"
+        default 4
+        range ENV_GPIO_RANGE_MIN ENV_GPIO_OUT_RANGE_MAX
+        help 
+            GPIO number where the DHT22 data pin is connected.
+            Make sure the pin supports input/output and has pull-up if needed.
+
+endmenu

+ 92 - 0
components/dht22/README.md

@@ -0,0 +1,92 @@
+# DHT22 Component for ESP-IDF
+
+Driver para el sensor de temperatura y humedad **DHT22** (AM2302) compatible con ESP-IDF.
+
+## Características
+
+- Lectura de temperatura (°C) y humedad relativa (%)
+- Comunicación bit-banging optimizada con protección contra interrupciones
+- Configuración del pin GPIO a través de `menuconfig`
+- Detección de errores (timeout y checksum)
+- Estructura lista para usar como componente reutilizable
+
+## Requisitos
+
+- ESP-IDF v5.0 o superior
+
+## Cómo añadir el componente a tu proyecto
+
+Agrega la siguiente dependencia en tu archivo `idf_component.yml`:
+
+```yaml
+dependencies:
+  dht22:
+    git: https://github.com/TU_USUARIO/TU_REPOSITORIO.git
+    version: "*"
+```
+
+## Configuración
+
+1. Ejecuta:
+
+```bash
+idf.py menuconfig
+```
+
+2. Ve a:
+
+`Component config → DHT22 configuration → DHT pin configuration`
+
+3. Selecciona el GPIO donde está conectado el sensor (por defecto: GPIO4).
+
+## Uso básico
+
+```c
+#include <stdio.h>
+#include "freertos/FreeRTOS.h"
+#include "freertos/task.h"
+#include "esp_log.h"
+#include "dht22.h"
+
+static const char *TAG = "DHT22";
+
+void app_main(void)
+{
+    float temperature = 0.0;
+    float humidity = 0.0;
+    esp_err_t ret;
+
+    ESP_LOGI(TAG, "Iniciando sensor DHT22...");
+
+    while (1) {
+        ret = dht_read(&temperature, &humidity);
+
+        if (ret == ESP_OK) {
+            ESP_LOGI(TAG, "Temperatura: %.1f °C | Humedad: %.1f %%", temperature, humidity);
+        } else {
+            ESP_LOGE(TAG, "Error al leer el sensor: %s", esp_err_to_name(ret));
+        }
+
+        // El DHT22 requiere al menos 2 segundos entre lecturas
+        vTaskDelay(pdMS_TO_TICKS(2500));
+    }
+}
+```
+
+## Conexiones (Wiring)
+
+| DHT22 Pin | ESP32 Pin | Descripción |
+|-----------|-----------|-------------|
+| VCC       | 3.3V      | Alimentación |
+| GND       | GND       | Tierra |
+| DATA      | GPIO4 (o el GPIO configurado) | Datos |
+
+- Recomendado: añadir una resistencia pull-up de 4.7kΩ a 10kΩ entre VCC y DATA.
+
+## Ejemplo completo
+
+Se incluye un ejemplo funcional en la carpeta `examples/dht22_example`.
+
+## Licencia
+
+Este proyecto está licenciado bajo la Licencia MIT.

+ 18 - 0
components/dht22/include/dht22.h

@@ -0,0 +1,18 @@
+#include <stdio.h>
+#include "freertos/FreeRTOS.h"
+#include "freertos/task.h"
+#include "driver/gpio.h"
+#include "esp_rom_sys.h"
+#include "esp_log.h"
+#include "sdkconfig.h"
+
+
+static esp_err_t dht_attach_pin();
+
+static esp_err_t get_change_time(uint8_t timeout_us, bool expected_level, uint32_t *time_us);
+
+static inline esp_err_t dht_communication(uint32_t *data);
+
+static inline int16_t data_to_int16(uint8_t MSB, uint8_t LSB);
+
+esp_err_t dht_read(float *temperature, float *humidity);

+ 114 - 0
components/dht22/src/dht22.c

@@ -0,0 +1,114 @@
+#include <stdio.h>
+#include "dht22.h"
+#include "freertos/FreeRTOS.h"
+#include "freertos/task.h"
+#include "driver/gpio.h"
+#include "esp_rom_sys.h"
+#include "esp_log.h"
+
+#define DHT_PIN CONFIG_DHT_PIN
+#define US_DELAY 3
+#define DHT_DATA_BITS 40
+
+static const char *TAG = "DHT22";
+
+static portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;
+
+// Macro to check the return value of a function and log an error if it is not ESP_OK
+#define CHECK_LOGE(x, msg, ...) do { \
+        esp_err_t __; \
+        if ((__ = x) != ESP_OK) { \
+            ESP_LOGE(TAG, msg, ## __VA_ARGS__); \
+            return __; \
+        } \
+    } while (0)
+
+
+
+static esp_err_t dht_attach_pin(){
+    if (DHT_PIN < GPIO_NUM_0 || DHT_PIN >= GPIO_NUM_MAX) {
+        ESP_LOGE(TAG, "Invalid GPIO pin number: %d", DHT_PIN);
+        return ESP_ERR_INVALID_ARG;
+    }
+    gpio_set_direction(DHT_PIN, GPIO_MODE_INPUT_OUTPUT_OD);
+    gpio_set_level(DHT_PIN, 1); // Set the pin high by default
+    return ESP_OK;
+}
+
+static esp_err_t get_change_time(uint8_t timeout_us, bool expected_level, uint32_t *time_us){
+    *time_us = 0;
+    while (*time_us < timeout_us){
+        if (gpio_get_level(DHT_PIN) == expected_level) {
+            return ESP_OK;
+        }
+        *time_us += US_DELAY;
+        esp_rom_delay_us(US_DELAY);
+    }
+    return ESP_ERR_TIMEOUT;
+}
+
+static inline esp_err_t dht_communication(uint32_t *data){
+    uint32_t high_time;
+    uint32_t low_time;
+
+    // Send start signal
+    gpio_set_direction(DHT_PIN, GPIO_MODE_INPUT_OUTPUT_OD);
+    gpio_set_level(DHT_PIN, 0);
+    esp_rom_delay_us(1500); // Pull low for at least 1ms
+    gpio_set_level(DHT_PIN, 1); // Release the line
+
+    CHECK_LOGE(get_change_time(44, 0, &low_time), "Failed to get dht response"); // Wait for the sensor to pull low 20-40us
+    CHECK_LOGE(get_change_time(88, 1, &high_time), "Failed to get dht response"); // Wait for the sensor to pull high 80us
+    CHECK_LOGE(get_change_time(88, 0, &low_time), "Failed to get dht response"); // Wait for the sensor to pull low 80us
+    
+    uint8_t checksum = 0;
+
+    for (uint8_t i = 0; i < DHT_DATA_BITS; i++){
+        
+        
+        // Wait for the sensor to pull low 50us
+        CHECK_LOGE(get_change_time(65, 1, &low_time), "Failed dht transmission %d h", i); 
+        
+        // Wait for the sensor to pull high 26-28us for 0 or 70us for 1
+        CHECK_LOGE(get_change_time(80, 0, &high_time), "Failed dht transmission %d l", i); 
+
+        if (i < 32){
+            *data |= ((high_time > low_time) << (31 - i)); // Set the bit if high_time is greater than low_time
+        }
+        else checksum |= (high_time > low_time) << (39 - i); // Calculate checksum in the last 8 bits
+
+    }
+    
+    if (checksum != (uint8_t)((*data >> 24) + (*data >> 16 & 0xFF) + (*data >> 8 & 0xFF) + (*data & 0xFF))) {
+        ESP_LOGE(TAG, "DHT22 checksum mismatch: calculated %02X, received %02X", checksum, *data & 0xFF);
+        return ESP_ERR_INVALID_CRC;
+    }
+
+    return ESP_OK;
+}
+
+static inline int16_t data_to_int16(uint8_t MSB, uint8_t LSB){
+    return (int16_t)((MSB << 8) | LSB);
+}
+
+
+esp_err_t dht_read(float *temperature, float *humidity){
+    uint32_t data = 0;
+
+    gpio_set_direction(DHT_PIN, GPIO_MODE_INPUT_OUTPUT_OD);
+    gpio_set_level(DHT_PIN, 1); 
+
+    portENTER_CRITICAL(&mux);
+    esp_err_t err = dht_communication(&data);
+    portEXIT_CRITICAL(&mux);
+
+    gpio_set_direction(DHT_PIN, GPIO_MODE_INPUT_OUTPUT_OD);
+    gpio_set_level(DHT_PIN, 1); 
+
+    if (err != ESP_OK) return err;
+
+
+    *humidity = data_to_int16(data >> 24 & 0xFF, data >> 16 & 0xFF) / 10.0;
+    *temperature = data_to_int16(data >> 8 & 0xFF, data & 0xFF) / 10.0;
+    return ESP_OK;
+}

+ 3 - 108
main/main.c

@@ -4,123 +4,18 @@
 #include "driver/gpio.h"
 #include "esp_rom_sys.h"
 #include "esp_log.h"
+#include "dht22.h"
 
-#define DHT_PIN GPIO_NUM_4
-#define US_DELAY 3
-#define DHT_DATA_BITS 40
 
 static const char *TAG = "DHT22";
 
-static portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;
-
-// Macro to check the return value of a function and log an error if it is not ESP_OK
-// portEXIT_CRITICAL(&mux);  despues del if
-#define CHECK_LOGE(x, msg, ...) do { \
-        esp_err_t __; \
-        if ((__ = x) != ESP_OK) { \
-            portEXIT_CRITICAL(&mux); \
-            ESP_LOGE(TAG, msg, ## __VA_ARGS__); \
-            return __; \
-        } \
-    } while (0)
-
-gpio_num_t dht_pin = DHT_PIN;
-
-
-static esp_err_t dht_attach_pin(gpio_num_t pin){
-    if (pin < GPIO_NUM_0 || pin >= GPIO_NUM_MAX) {
-        ESP_LOGE(TAG, "Invalid GPIO pin number: %d", pin);
-        return ESP_ERR_INVALID_ARG;
-    }
-    gpio_set_direction(pin, GPIO_MODE_INPUT_OUTPUT_OD);
-    gpio_set_level(pin, 1); // Set the pin high by default
-    return ESP_OK;
-}
-
-static esp_err_t get_change_time(gpio_num_t pin, uint8_t timeout_us, bool expected_level, uint32_t *time_us){
-    *time_us = 0;
-    while (*time_us < timeout_us){
-        if (gpio_get_level(pin) == expected_level) {
-            return ESP_OK;
-        }
-        *time_us += US_DELAY;
-        esp_rom_delay_us(US_DELAY);
-    }
-    return ESP_ERR_TIMEOUT;
-}
-
-static inline esp_err_t dht_communication(gpio_num_t pin, uint32_t *data){
-    uint32_t high_time;
-    uint32_t low_time;
-
-    // Send start signal
-    gpio_set_direction(pin, GPIO_MODE_INPUT_OUTPUT_OD);
-    gpio_set_level(pin, 0);
-    esp_rom_delay_us(1500); // Pull low for at least 1ms
-    gpio_set_level(pin, 1); // Release the line
-
-    CHECK_LOGE(get_change_time(pin, 44, 0, &low_time), "Failed to get dht response"); // Wait for the sensor to pull low 20-40us
-    CHECK_LOGE(get_change_time(pin, 88, 1, &high_time), "Failed to get dht response"); // Wait for the sensor to pull high 80us
-    CHECK_LOGE(get_change_time(pin, 88, 0, &low_time), "Failed to get dht response"); // Wait for the sensor to pull low 80us
-    
-    uint8_t checksum = 0;
-
-    for (uint8_t i = 0; i < DHT_DATA_BITS; i++){
-        
-        
-        // Wait for the sensor to pull low 50us
-        CHECK_LOGE(get_change_time(pin, 65, 1, &low_time), "Failed dht transmission %d h", i); 
-        
-        // Wait for the sensor to pull high 26-28us for 0 or 70us for 1
-        CHECK_LOGE(get_change_time(pin, 80, 0, &high_time), "Failed dht transmission %d l", i); 
-
-        if (i < 32){
-            *data |= ((high_time > low_time) << (31 - i)); // Set the bit if high_time is greater than low_time
-        }
-        else checksum |= (high_time > low_time) << (39 - i); // Calculate checksum in the last 8 bits
-
-    }
-    
-    if (checksum != (uint8_t)((*data >> 24) + (*data >> 16 & 0xFF) + (*data >> 8 & 0xFF) + (*data & 0xFF))) {
-        ESP_LOGE(TAG, "DHT22 checksum mismatch: calculated %02X, received %02X", checksum, *data & 0xFF);
-        return ESP_ERR_INVALID_CRC;
-    }
-
-    return ESP_OK;
-}
-
-static inline int16_t data_to_int16(uint8_t MSB, uint8_t LSB){
-    return (int16_t)((MSB << 8) | LSB);
-}
-
-
-esp_err_t dht_read(gpio_num_t pin, float *temperature, float *humidity){
-    uint32_t data = 0;
-
-    gpio_set_direction(pin, GPIO_MODE_INPUT_OUTPUT_OD);
-    gpio_set_level(pin, 1); 
-
-    portENTER_CRITICAL(&mux);
-    esp_err_t err = dht_communication(pin, &data);
-    portEXIT_CRITICAL(&mux);
-
-    gpio_set_direction(pin, GPIO_MODE_INPUT_OUTPUT_OD);
-    gpio_set_level(pin, 1); 
-
-    if (err != ESP_OK) return err;
-
-
-    *humidity = data_to_int16(data >> 24 & 0xFF, data >> 16 & 0xFF) / 10.0;
-    *temperature = data_to_int16(data >> 8 & 0xFF, data & 0xFF) / 10.0;
-    return ESP_OK;
-}
 
 void app_main(void)
 {
     
     float temperature;
     float humidity;
-    esp_err_t err = dht_attach_pin(dht_pin);
+    esp_err_t err = dht_attach_pin();
     if (err != ESP_OK) {
         ESP_LOGE(TAG, "Failed to attach DHT pin: %s", esp_err_to_name(err));
         vTaskDelay(pdMS_TO_TICKS(5000)); // Wait for 5 seconds before retrying
@@ -128,7 +23,7 @@ void app_main(void)
     }
     vTaskDelay(pdMS_TO_TICKS(2000)); // Wait for 2 seconds before starting the main loop
     while (1) {
-        if (dht_read(dht_pin, &temperature, &humidity) == ESP_OK) {
+        if (dht_read(&temperature, &humidity) == ESP_OK) {
             ESP_LOGI(TAG, "Temperature: %.1f°C, Humidity: %.1f%%", temperature, humidity);
         } else {
             ESP_LOGE(TAG, "Failed to read from DHT22 sensor");