Просмотр исходного кода

codigo completo, a falta de pruebas

dacowars 1 неделя назад
Родитель
Сommit
845f9dfff2
3 измененных файлов с 436 добавлено и 328 удалено
  1. 1 1
      main/CMakeLists.txt
  2. 6 0
      main/Kconfig.projbuild
  3. 429 327
      main/main.c

+ 1 - 1
main/CMakeLists.txt

@@ -1,4 +1,4 @@
 idf_component_register(SRCS "main.c"
                     INCLUDE_DIRS "."
-                    REQUIRES driver dht22 esp_driver_uart GPS_parser fatfs
+                    REQUIRES driver dht22 esp_driver_uart GPS_parser fatfs esp_wifi esp_event esp_http_server
                     WHOLE_ARCHIVE)

+ 6 - 0
main/Kconfig.projbuild

@@ -48,4 +48,10 @@ menu "SD SPI Example Configuration"
         help 
             GPIO number where the OLED display SCL pin is connected.  
 
+    config PIN_BUTTON
+        int "Button pin configuration"
+        default 4
+        range ENV_GPIO_RANGE_MIN ENV_GPIO_OUT_RANGE_MAX
+        help 
+            GPIO number where the button is connected.
 endmenu

+ 429 - 327
main/main.c

@@ -22,6 +22,9 @@
 #include "esp_http_server.h"
 #include "lwip/inet.h"
 #include "sys/stat.h"
+#include "driver/gpio.h"
+#include "esp_attr.h"
+#include "esp_pm.h"
 
 const char *DHT_TAG = "DHT22";
 const char *GPS_TAG = "GPS_PARSER";
@@ -42,10 +45,14 @@ const char *GEN_TAG = "General";
 #define PIN_TX GPIO_NUM_17
 #define PIN_RX GPIO_NUM_16
 
+#define PIN_BUTTON CONFIG_PIN_BUTTON
+
 //definicion de tiempos de pulsacion
 #define PULSACION_LARGA_MS 2000
 #define DURACION_WATCHDOG_MS 10000
 
+#define WIFI_TIMEOUT_MS 3000000
+
 #define MEASUREMENT_INTERVAL_S 1
 
 #define DEG2RAD (M_PI/180.0)
@@ -62,7 +69,7 @@ static esp_netif_t *ap_netif = NULL;
 static bool wifiActivado = false;
 static uint32_t wifiLastActivity = 0;
 
-extern char filename[13]; // tu archivo gpx
+extern char filename[64]; // tu archivo gpx
 const char *apSSID = "MiAP";
 const char *apPassword = "password123";
 
@@ -91,12 +98,194 @@ int pantallaEstado_menu = -1; //maquina de estados cuando no se esta grabando ru
 float distancia_total = 0.0;
 volatile unsigned long ignore_isr_until = 0; //para debounce
 
-char filename[13] = "/panchas.gpx";
+char filename[64] = "/panchas.gpx";
 
 ssd1306_handle_t d = NULL;
+i2c_master_dev_handle_t i2c_dev_handle = NULL;
 
 const char mount_point[] = MOUNT_POINT;
 
+// Configuración del GPIO del botón
+gpio_config_t btn_cfg = {
+    .pin_bit_mask = (1ULL << PIN_BUTTON),
+    .mode         = GPIO_MODE_INPUT,
+    .pull_up_en   = GPIO_PULLUP_ENABLE,
+    .pull_down_en = GPIO_PULLDOWN_DISABLE,
+    .intr_type    = GPIO_INTR_NEGEDGE,  // FALLING = flanco de bajada
+};
+
+void uart_configurator() {
+    // Configure UART parameters
+    uart_config_t uart_config = {
+        .baud_rate = 115200,
+        .data_bits = UART_DATA_8_BITS,
+        .parity = UART_PARITY_DISABLE,
+        .stop_bits = UART_STOP_BITS_1,
+        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE
+    };
+    QueueHandle_t uart_queue;
+    // Install UART driver using an event queue here
+    ESP_ERROR_CHECK(uart_driver_install(UART_NUM_2, uart_buffer_size, uart_buffer_size, 10, &uart_queue, 0));
+    ESP_ERROR_CHECK(uart_param_config(UART_NUM_2, &uart_config));
+    ESP_ERROR_CHECK(uart_set_pin(UART_NUM_2, PIN_TX, PIN_RX, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE));
+}
+
+// Init i2c
+static i2c_master_bus_handle_t i2c_bus0_init(gpio_num_t sda, gpio_num_t scl, uint32_t hz) {
+    i2c_master_bus_config_t bus_cfg = {
+        .i2c_port                     = I2C_NUM_0,
+        .sda_io_num                   = sda,
+        .scl_io_num                   = scl,
+        .clk_source                   = I2C_CLK_SRC_DEFAULT,
+        .glitch_ignore_cnt            = 0,
+        .flags.enable_internal_pullup = true,
+    };
+    i2c_master_bus_handle_t bus = NULL;
+    ESP_ERROR_CHECK(i2c_new_master_bus(&bus_cfg, &bus));
+    // NOTE: per-device speed is set when adding the device (in driver bind).
+    return bus;
+}
+
+static esp_err_t wifi_ap_init(void)
+{
+
+    ESP_ERROR_CHECK(esp_netif_init());
+    ESP_ERROR_CHECK(esp_event_loop_create_default());
+
+    ap_netif = esp_netif_create_default_wifi_ap();
+    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
+    ESP_ERROR_CHECK(esp_wifi_init(&cfg));
+    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP));
+
+    wifi_config_t wifi_config = {
+        .ap = {
+            .ssid = "",
+            .ssid_len = 0,
+            .channel = 1,
+            .password = "",
+            .max_connection = 4,
+            .authmode = WIFI_AUTH_WPA_WPA2_PSK,
+        },
+    };
+
+    strncpy((char *)wifi_config.ap.ssid, apSSID, sizeof(wifi_config.ap.ssid) - 1);
+    strncpy((char *)wifi_config.ap.password, apPassword, sizeof(wifi_config.ap.password) - 1);
+
+    if (strlen(apPassword) == 0) {
+        wifi_config.ap.authmode = WIFI_AUTH_OPEN;
+    }
+
+    ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_AP, &wifi_config));
+    ESP_ERROR_CHECK(esp_wifi_start());
+    return ESP_OK;
+}
+
+static esp_err_t get_ap_ip(char *out_ip, size_t len)
+{
+    esp_netif_ip_info_t ip_info;
+    if (ap_netif == NULL) {
+        return ESP_ERR_INVALID_STATE;
+    }
+    ESP_ERROR_CHECK(esp_netif_get_ip_info(ap_netif, &ip_info));
+    inet_ntoa_r(ip_info.ip, out_ip, len);
+    return ESP_OK;
+}
+
+static esp_err_t root_get_handler(httpd_req_t *req)
+{
+    wifiLastActivity = xTaskGetTickCount();
+
+    char ip_str[16] = {0};
+    get_ap_ip(ip_str, sizeof(ip_str));
+
+    const char *nombreArchivo = (filename[0] == '/') ? filename + 1 : filename;
+
+    char html[1024];
+    snprintf(html, sizeof(html),
+        "<!DOCTYPE html><html><head><meta charset='UTF-8'><title>ESP32 GPS Logger</title>"
+        "<style>body{font-family:Arial;text-align:center;margin:50px;}h1{color:#333;} "
+        "a.button{background:#4CAF50;color:white;padding:20px 40px;text-decoration:none;"
+        "font-size:24px;border-radius:12px;display:inline-block;margin:20px;}</style></head>"
+        "<body><h1>GPS Logger</h1><p>Archivo listo para descargar:</p>"
+        "<a href='/download' class='button' download='%s'>Descargar %s</a>"
+        "<hr><p>IP: %s</p><p>Se apagará en 5 min sin uso.</p></body></html>",
+        nombreArchivo, nombreArchivo, ip_str);
+
+    httpd_resp_set_type(req, "text/html");
+    return httpd_resp_send(req, html, HTTPD_RESP_USE_STRLEN);
+}
+
+static esp_err_t stream_file_response(httpd_req_t *req, FILE *file)
+{
+    char buf[1024];
+    size_t read_len;
+    esp_err_t ret;
+
+    while ((read_len = fread(buf, 1, sizeof(buf), file)) > 0) {
+        ret = httpd_resp_send_chunk(req, buf, read_len);
+        if (ret != ESP_OK) {
+            fclose(file);
+            return ret;
+        }
+    }
+
+    fclose(file);
+    return httpd_resp_send_chunk(req, NULL, 0);
+}
+
+static esp_err_t download_get_handler(httpd_req_t *req)
+{
+    wifiLastActivity = xTaskGetTickCount();
+
+    struct stat st;
+    if (stat(filename, &st) != 0) {
+        httpd_resp_send_404(req);
+        return ESP_FAIL;
+    }
+
+    FILE *file = fopen(filename, "r");
+    if (!file) {
+        httpd_resp_send_404(req);
+        return ESP_FAIL;
+    }
+
+    const char *nombreArchivo = (filename[0] == '/') ? filename + 1 : filename;
+    char disposition[128];
+    snprintf(disposition, sizeof(disposition),
+             "attachment; filename=\"%s\"", nombreArchivo);
+
+    httpd_resp_set_type(req, "application/gpx+xml");
+    httpd_resp_set_hdr(req, "Content-Disposition", disposition);
+    
+    return stream_file_response(req, file);
+}
+
+static const httpd_uri_t root_uri = {
+    .uri       = "/",
+    .method    = HTTP_GET,
+    .handler   = root_get_handler,
+    .user_ctx  = NULL
+};
+
+static const httpd_uri_t download_uri = {
+    .uri       = "/download",
+    .method    = HTTP_GET,
+    .handler   = download_get_handler,
+    .user_ctx  = NULL
+};
+
+static esp_err_t iniciar_servidor_http(void)
+{
+    httpd_config_t config = HTTPD_DEFAULT_CONFIG();
+    if (httpd_start(&http_server, &config) != ESP_OK) {
+        return ESP_FAIL;
+    }
+
+    httpd_register_uri_handler(http_server, &root_uri);
+    httpd_register_uri_handler(http_server, &download_uri);
+    return ESP_OK;
+}
+
 void OLED_test(){
 
     i2c_master_bus_handle_t i2c_bus = i2c_bus0_init(PIN_NUM_SDA, PIN_NUM_SCL, 400000);
@@ -114,6 +303,13 @@ void OLED_test(){
             },
     };
 
+    i2c_device_config_t dev_cfg = {
+        .dev_addr_length = I2C_ADDR_BIT_LEN_7,
+        .device_address  = 0x3C,
+        .scl_speed_hz    = 400000,
+    };
+    i2c_master_bus_add_device(i2c_bus, &dev_cfg, &i2c_dev_handle);
+
     ESP_ERROR_CHECK(ssd1306_new_i2c(&cfg, &d));
 
     ESP_ERROR_CHECK(ssd1306_clear(d));
@@ -365,17 +561,23 @@ void task_mediciones(void *pvParameters) {
 void crear_archivo(){
     int num = 1;
 
-    sprintf(filename, MOUNT_POINT"/data%03d.gpx", num);
+    char nombre[32];
 
-    FILE *f = fopen(filename, "r");
+    snprintf(nombre, sizeof(nombre), "data%03d.gpx", num);
+    snprintf(filename, sizeof(filename), "%s/%s", MOUNT_POINT, nombre);
 
+    FILE *f = fopen(filename, "r");
     while (f != NULL) {
+        fclose(f);
         num++;
-        sprintf(filename, MOUNT_POINT"/data%03d.gpx", num);
-        FILE *f = fopen(filename, "r");
+        snprintf(nombre, sizeof(nombre), "data%03d.gpx", num);
+        snprintf(filename, sizeof(filename), "%s/%s", MOUNT_POINT, nombre);
+        f = fopen(filename, "r");
     }
 
-    FILE *f = fopen(filename, "w");
+    fclose(f);
+
+    f = fopen(filename, "w");
 
     char buffer[50];
 
@@ -461,352 +663,252 @@ void desactivarWiFi(void)
     OLED_print("WiFi", "Apagado");
 }
 
-void app_main(void)
-{
-    // Initialize DHT22 sensor
-    /*
-    float temperature;
-    float humidity;
-    esp_err_t err = dht_attach_pin();
-    if (err != ESP_OK) {
-        ESP_LOGE(DHT_TAG, "Failed to attach DHT pin: %s", esp_err_to_name(err));
-        vTaskDelay(pdMS_TO_TICKS(5000)); // Wait for 5 seconds before retrying
-        return;
-    }
-    vTaskDelay(pdMS_TO_TICKS(2000)); // Wait for 2 seconds before starting the main loop
-    while (1) {
-        if (dht_read(&temperature, &humidity) == ESP_OK) {
-            ESP_LOGI(DHT_TAG, "Temperature: %.1f°C, Humidity: %.1f%%", temperature, humidity);
-        } else {
-            ESP_LOGE(DHT_TAG, "Failed to read from DHT22 sensor");
-        }
-        vTaskDelay(pdMS_TO_TICKS(5000)); // Wait for 5 seconds before the next reading
+void IRAM_ATTR isr_button(void *arg) {
+    unsigned long now = pdTICKS_TO_MS(xTaskGetTickCount());
+    if (now < ignore_isr_until) {
+        return; // Ignorar interrupción si está dentro del período de debounce
     }
-    */
-    // Initialize GPS parser
-    /*
-    uart_configurator();
-    double latitude, longitude;
-    gps_parser_init(&gps);
-    while(1){
-        while (uart_read_bytes(UART_NUM_2, &data, 1, 0)){
-            gps_parser_encode(&gps, data);
-        }
-        if (gps_location_is_valid(&gps.location)) {
-            double lat = gps_location_lat(&gps.location);
-            double lng = gps_location_lng(&gps.location);
-            ESP_LOGI(GPS_TAG, "Lat: %.8f, Lng: %.8f", lat, lng);
-        }
-
-        if (gps_date_is_valid(&gps.date) && gps_time_is_valid(&gps.time)) {
-            ESP_LOGI(GPS_TAG, "Fecha: %02u/%02u/%04u Hora: %02u:%02u:%02u\n",
-                    gps_date_day(&gps.date),
-                    gps_date_month(&gps.date),
-                    gps_date_year(&gps.date),
-                    gps_time_hour(&gps.time),
-                    gps_time_minute(&gps.time),
-                    gps_time_second(&gps.time));
+    static unsigned long lastInterrupt = 0;
+    
+    if ((now - lastInterrupt) > 300 ){ // debounce de 300 ms 
+        BaseType_t xHigherPriorityTaskWoken = pdFALSE;
+        xSemaphoreGiveFromISR(buttonSemaphore, &xHigherPriorityTaskWoken); 
+        lastInterrupt = now;
+        if (xHigherPriorityTaskWoken) {
+            portYIELD_FROM_ISR();
         }
-        vTaskDelay(pdMS_TO_TICKS(2000)); // Wait for 1 second before the next reading
-    }
-    */
-
-    // Initialize SD card
-    /*
-    esp_vfs_fat_sdmmc_mount_config_t mount_config = {
-        .format_if_mount_failed = false,
-        .max_files = 5,
-        .allocation_unit_size = 16 * 1024
-    };
+    } 
+}
 
-    sdmmc_card_t *card;
+void drawProgressBar(int x, int y, int w, int h, unsigned long progress, unsigned long total) {
+    int filledWidth = (progress * w) / total;
+    ESP_ERROR_CHECK(ssd1306_draw_rect(d, x, y, filledWidth, h, true));  //dibuja un trozo de rectangulo relleno
+    ESP_ERROR_CHECK(ssd1306_draw_rect(d, x + filledWidth, y, w - filledWidth, h, false)); //dibuja el resto del rectangulo vacio
+    ESP_ERROR_CHECK(ssd1306_display(d));
+}
 
-    const char mount_point[] = MOUNT_POINT;
+void task_ui(void *pvParameters){
+    unsigned long pressTime = 0;
+    unsigned long lastActivity = pdTICKS_TO_MS(xTaskGetTickCount());
+    bool pantallaOn = true; //comprobar el estado inicial, no se cual sera
+    bool processingButton = false;
 
-    sdmmc_host_t host = SDSPI_HOST_DEFAULT();
-    host.max_freq_khz = 9000; //a mas freq no funciona, porque pipas
+    while(1){
+        if (xSemaphoreTake(buttonSemaphore, pdMS_TO_TICKS(200)) == pdTRUE){ //button pressed
+        if (processingButton) continue; //evita reentradas
+        processingButton = true;
 
-    spi_bus_config_t bus_cfg = {
-        .mosi_io_num = PIN_NUM_MOSI,
-        .miso_io_num = PIN_NUM_MISO,
-        .sclk_io_num = PIN_NUM_CLK,
-        .quadwp_io_num = -1,
-        .quadhd_io_num = -1,
-        .max_transfer_sz = 4092,
-    };
+        pressTime = pdTICKS_TO_MS(xTaskGetTickCount());
+        lastActivity = pdTICKS_TO_MS(xTaskGetTickCount()); //reset watchdog
 
-    esp_err_t ret = spi_bus_initialize(host.slot, &bus_cfg, SDSPI_DEFAULT_DMA);
-    if (ret != ESP_OK) {
-        ESP_LOGE(SD_TAG, "Failed to initialize bus.");
-        return;
-    }
+        if (!pantallaOn){
+            uint8_t cmd_on[] = {0x00, 0xAF};
+            i2c_master_transmit(i2c_dev_handle, cmd_on, sizeof(cmd_on), pdMS_TO_TICKS(100));
+            pantallaOn = true;
+        }
 
-    gpio_set_pull_mode(PIN_NUM_MISO, GPIO_PULLUP_ONLY);
+        bool timed_out = false;
+        unsigned long checkTime = pdTICKS_TO_MS(xTaskGetTickCount());
+        while (gpio_get_level(PIN_BUTTON) == 0){
+            vTaskDelay(pdMS_TO_TICKS(10));
+            checkTime = pdTICKS_TO_MS(xTaskGetTickCount());
+            if ((checkTime - pressTime) > DURACION_WATCHDOG_MS){ //10s timeout para evitar bloqueos
+                timed_out = true;
+                break;
+            }
+            drawProgressBar(0, 64 - 10, 128, 8, checkTime - pressTime, PULSACION_LARGA_MS);
+        }
 
-    sdspi_device_config_t slot_config = SDSPI_DEVICE_CONFIG_DEFAULT();
-    slot_config.gpio_cs = PIN_NUM_CS;
-    slot_config.host_id = host.slot;
+        ignore_isr_until = pdTICKS_TO_MS(xTaskGetTickCount()) + 500; //ignorar nuevas interrupciones durante 500 ms
 
-    ESP_LOGI(SD_TAG, "Mounting filesystem");
-    ret = esp_vfs_fat_sdspi_mount(mount_point, &host, &slot_config, &mount_config, &card);
+        unsigned long duration = checkTime - pressTime;
 
-    if (ret != ESP_OK) {
-        if (ret == ESP_FAIL) {
-            ESP_LOGE(SD_TAG, "Failed to mount filesystem. "
-                     "If you want the card to be formatted, set the CONFIG_EXAMPLE_FORMAT_IF_MOUNT_FAILED menuconfig option.");
+        if (timed_out){
+            OLED_print("Apagando","pantalla");
+            uint8_t cmd_off[] = {0x00, 0xAE};
+            i2c_master_transmit(i2c_dev_handle, cmd_off, sizeof(cmd_off), pdMS_TO_TICKS(100));
+            pantallaOn = false;
         } else {
-            ESP_LOGE(SD_TAG, "Failed to initialize the card (%s). "
-                     "Make sure SD card lines have pull-up resistors in place.", esp_err_to_name(ret));
+            if (grabando){
+                if (duration >= PULSACION_LARGA_MS){
+                    grabando = false;
+                    vTaskSuspend(medicionesHandle);
+                    OLED_print("Ruta","pausada");
+                } else {
+                    pantallaEstado_grab = (pantallaEstado_grab + 1) % 5; //cicla entre 0-4
+                    struct SensorData currentData;
+                    if(xSemaphoreTake(dataMutex, portMAX_DELAY) == pdTRUE){
+                        currentData = latestData;
+                        xSemaphoreGive(dataMutex);
+                    }
+                    switch (pantallaEstado_grab){
+                        char line2[32];
+                        case 0:
+                            snprintf(line2, sizeof(line2), "%.4f,%.4f", currentData.longitude, currentData.latitude);
+                            OLED_print("Posicion", line2);
+                            break;
+                        case 1:
+                            snprintf(line2, sizeof(line2), "%.1fkm", distancia_total);
+                            OLED_print("Distancia", line2);
+                            break;
+                        case 2:
+                            snprintf(line2, sizeof(line2), "%.1fm", currentData.altura);
+                            OLED_print("Altitud", line2);
+                            break;
+                        case 3:
+                            snprintf(line2, sizeof(line2), "%.1fC/%.1f%%", currentData.temperature, currentData.humidity);
+                            OLED_print("Temp/Hum", line2);
+                            break;
+                        case 4:
+                            snprintf(line2, sizeof(line2), "%.1fkm/h", currentData.velocidad);
+                            OLED_print("Velocidad", line2);
+                            break;
+                    }
+                }
+            } else {
+                if (duration >= PULSACION_LARGA_MS){
+                    switch (pantallaEstado_menu){
+                        case 0:
+                            //activar la ruta y crear el archivo
+                            crear_archivo();
+                            vTaskResume(medicionesHandle);
+                            OLED_print("Ruta","iniciada");
+                            finalizado = false;
+                            grabando = true;
+                            break;
+                        case 1:
+                            //cerrar el archivo y cambiar el valor de 'filename'
+                            cerrar_archivo();
+                            finalizado = true;
+                            break;
+                        case 2:
+                            //implementacion wifi
+                            if(!wifiActivado){
+                                activarWiFi();
+                            } else {
+                                desactivarWiFi();
+                            }
+                            break;
+                    }
+                } else {
+                    pantallaEstado_menu = (pantallaEstado_menu + 1) % 3;
+                    int previous_state = -1;
+                    while (pantallaEstado_menu != previous_state) {
+                        previous_state = pantallaEstado_menu;
+                        switch (pantallaEstado_menu) {
+                            case 0:
+                                if (!finalizado) OLED_print("Reanudar","ruta");
+                                else OLED_print("Iniciar","ruta");
+                                break;
+                            case 1:
+                                FILE *f = fopen(filename, "r");
+                                if (f && !finalizado) {
+                                    OLED_print("Finalizar","ruta");
+                                    break;
+                                } else {
+                                    pantallaEstado_menu = (pantallaEstado_menu + 1) % 3;
+                                }
+                                break;
+                            case 2:
+                                if (finalizado) { 
+                                    OLED_print("Conexion","WiFi");
+                                    break;
+                                } else {
+                                    pantallaEstado_menu = (pantallaEstado_menu + 1) % 3;
+                                }
+                                break;
+                        }
+                    }
+                }
+            }        
+        }
+        lastActivity = pdTICKS_TO_MS(xTaskGetTickCount());  //reset watchdog
+        processingButton = false;
+        vTaskDelay(pdMS_TO_TICKS(100)); //pequeño delay para no busy waiting
+        }
+        //check watchdog fuera del boton
+        if (pantallaOn && ((pdTICKS_TO_MS(xTaskGetTickCount()) - lastActivity) > DURACION_WATCHDOG_MS)){
+            uint8_t cmd_off[] = {0x00, 0xAE};
+            i2c_master_transmit(i2c_dev_handle, cmd_off, sizeof(cmd_off), pdMS_TO_TICKS(100));
+            pantallaOn = false;
+        }
+        //check wifi timeout
+        if (wifiActivado) {
+            // server.handleClient() → NO necesario, httpd corre en su propio task
+
+            // WiFi.softAPgetStationNum() → esp_wifi_ap_get_sta_list()
+            wifi_sta_list_t sta_list;
+            if (esp_wifi_ap_get_sta_list(&sta_list) == ESP_OK && sta_list.num > 0) {
+                wifiLastActivity = pdTICKS_TO_MS(xTaskGetTickCount());
+            }
+
+            if ((pdTICKS_TO_MS(xTaskGetTickCount()) - wifiLastActivity) > WIFI_TIMEOUT_MS) {
+                desactivarWiFi();
+            }
         }
-        return;
-    }
-    ESP_LOGI(SD_TAG, "Filesystem mounted");
-
-    // Card has been initialized, print its properties
-    sdmmc_card_print_info(stdout, card);
-
-    const char *file_foo = MOUNT_POINT"/foo.txt";
-
-    // Check if destination file exists before renaming
-    struct stat st;
-    if (stat(file_foo, &st) == 0) {
-        // Delete it if it exists
-        unlink(file_foo);
-    }
-
-    const char *file_nihao = MOUNT_POINT"/nihao.txt";
-
-    // All done, unmount partition and disable SPI peripheral
-    esp_vfs_fat_sdcard_unmount(mount_point, card);
-    ESP_LOGI(SD_TAG, "Card unmounted");
-
-    //deinitialize the bus after all devices are removed
-    spi_bus_free(host.slot);
-    */
-
-    // Initialize display
-    /*
-    i2c_master_bus_handle_t i2c_bus =
-        i2c_bus0_init(GPIO_NUM_21, GPIO_NUM_22, 400000);
-
-    ssd1306_config_t cfg = {
-        .width  = 128,
-        .height = 64,
-        .fb     = NULL, // let driver allocate internally
-        .fb_len = 0,
-        .iface.i2c =
-            {
-                .port     = I2C_NUM_0,
-                .addr     = 0x3C,        // typical SSD1306 I2C address
-                .rst_gpio = GPIO_NUM_NC, // no reset pin
-            },
-    };
-
-    ssd1306_handle_t d = NULL;
-    ESP_ERROR_CHECK(ssd1306_new_i2c(&cfg, &d));
-
-    // ----- Clear screen -----
-    ESP_ERROR_CHECK(ssd1306_clear(d));
-
-    // ----- Draw pixels in corners of screen -----
-    ESP_ERROR_CHECK(ssd1306_draw_pixel(d, 0, 0, true));
-    ESP_ERROR_CHECK(ssd1306_draw_pixel(d, cfg.width - 1, 0, true));
-    ESP_ERROR_CHECK(ssd1306_draw_pixel(d, 0, cfg.height - 1, true));
-    ESP_ERROR_CHECK(ssd1306_draw_pixel(d, cfg.width - 1, cfg.height - 1, true));
-
-    // ----- Draw rectangles -----
-    ESP_ERROR_CHECK(ssd1306_draw_rect(d, 2, 2, 40, 20, false));
-    ESP_ERROR_CHECK(ssd1306_draw_rect(d, 2, 24, 32, 16, true));
-
-    // ----- Draw circles -----
-    ESP_ERROR_CHECK(ssd1306_draw_circle(d, 32, 52, 8, true));
-    ESP_ERROR_CHECK(ssd1306_draw_circle(d, 100, 52, 4, false));
-
-    // ----- Draw lines -----
-    ESP_ERROR_CHECK(ssd1306_draw_line(d, 2, 2, 40, 20, true));
-    ESP_ERROR_CHECK(ssd1306_draw_line(d, 32, 52, 100, 52, true));
-
-    // ----- Draw text -----
-    ESP_ERROR_CHECK(ssd1306_draw_text(d, 48, 2, "OK!", true));
-    ESP_ERROR_CHECK(
-        ssd1306_draw_text_scaled(d, 48, 10, "Hello\nWorld!", true, 2));
-
-    ESP_ERROR_CHECK(ssd1306_display(d));
-
-    ESP_LOGI(OLED_TAG, "Display updated successfully.");
-    */
-}
-
-
-void uart_configurator() {
-    // Configure UART parameters
-    uart_config_t uart_config = {
-        .baud_rate = 115200,
-        .data_bits = UART_DATA_8_BITS,
-        .parity = UART_PARITY_DISABLE,
-        .stop_bits = UART_STOP_BITS_1,
-        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE
-    };
-    QueueHandle_t uart_queue;
-    // Install UART driver using an event queue here
-    ESP_ERROR_CHECK(uart_driver_install(UART_NUM_2, uart_buffer_size, uart_buffer_size, 10, &uart_queue, 0));
-    ESP_ERROR_CHECK(uart_param_config(UART_NUM_2, &uart_config));
-    ESP_ERROR_CHECK(uart_set_pin(UART_NUM_2, PIN_TX, PIN_RX, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE));
-}
-
-static esp_err_t s_example_write_file(const char *path, char *data)
-{
-    ESP_LOGI(SD_TAG, "Opening file %s", path);
-    FILE *f = fopen(path, "w");
-    if (f == NULL) {
-        ESP_LOGE(SD_TAG, "Failed to open file for writing");
-        return ESP_FAIL;
     }
-    fprintf(f, data);
-    fclose(f);
-    ESP_LOGI(SD_TAG, "File written");
-
-    return ESP_OK;
 }
 
-// Init i2c
-static i2c_master_bus_handle_t i2c_bus0_init(gpio_num_t sda, gpio_num_t scl, uint32_t hz) {
-    i2c_master_bus_config_t bus_cfg = {
-        .i2c_port                     = I2C_NUM_0,
-        .sda_io_num                   = sda,
-        .scl_io_num                   = scl,
-        .clk_source                   = I2C_CLK_SRC_DEFAULT,
-        .glitch_ignore_cnt            = 0,
-        .flags.enable_internal_pullup = true,
-    };
-    i2c_master_bus_handle_t bus = NULL;
-    ESP_ERROR_CHECK(i2c_new_master_bus(&bus_cfg, &bus));
-    // NOTE: per-device speed is set when adding the device (in driver bind).
-    return bus;
-}
+void app_main(void) {
 
-static esp_err_t wifi_ap_init(void)
-{
-    esp_err_t err;
+    gpio_config(&btn_cfg);
 
-    ESP_ERROR_CHECK(esp_netif_init());
-    ESP_ERROR_CHECK(esp_event_loop_create_default());
+    // Instalar el servicio de interrupciones y adjuntar la ISR
+    gpio_install_isr_service(0);
+    gpio_isr_handler_add(PIN_BUTTON, isr_button, NULL);
+    
+    buttonSemaphore = xSemaphoreCreateBinary();
+    dataMutex = xSemaphoreCreateMutex();
 
-    ap_netif = esp_netif_create_default_wifi_ap();
-    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
-    ESP_ERROR_CHECK(esp_wifi_init(&cfg));
-    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP));
+    // OLED check
+    OLED_test();
+    vTaskDelay(pdMS_TO_TICKS(1000));
+    // DHT check
+    DHT_test();
+    vTaskDelay(pdMS_TO_TICKS(1000));
+    // SD Card check
+    SD_test();
+    vTaskDelay(pdMS_TO_TICKS(1000));
+    // GPS check
+    GPS_test_wait();
+    vTaskDelay(pdMS_TO_TICKS(2000));
 
-    wifi_config_t wifi_config = {
-        .ap = {
-            .ssid = "",
-            .ssid_len = 0,
-            .channel = 1,
-            .password = "",
-            .max_connection = 4,
-            .authmode = WIFI_AUTH_WPA_WPA2_PSK,
-        },
+    // Crear tarea para mediciones
+    xTaskCreatePinnedToCore(
+        task_mediciones,     // Función de la tarea
+        "Mediciones",        // Nombre de la tarea
+        8192,                // Tamaño del stack
+        NULL,     // Parámetro de la tarea
+        10,                   // Prioridad de la tarea
+        &medicionesHandle,                // Handle de la tarea
+        0                    // Núcleo donde se ejecuta
+    );
+
+    xTaskCreatePinnedToCore(
+        task_ui,             // Función de la tarea
+        "UI",                // Nombre de la tarea
+        8192,                // Tamaño del stack
+        NULL,                // Parámetro de la tarea
+        5,                   // Prioridad de la tarea
+        NULL,                // Handle de la tarea
+        1                    // Núcleo donde se ejecuta
+    );
+
+    esp_pm_config_t pm_config = {
+        .max_freq_mhz = 240,
+        .min_freq_mhz = 80,
+        .light_sleep_enable = true
     };
 
-    strncpy((char *)wifi_config.ap.ssid, apSSID, sizeof(wifi_config.ap.ssid) - 1);
-    strncpy((char *)wifi_config.ap.password, apPassword, sizeof(wifi_config.ap.password) - 1);
-
-    if (strlen(apPassword) == 0) {
-        wifi_config.ap.authmode = WIFI_AUTH_OPEN;
-    }
-
-    ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_AP, &wifi_config));
-    ESP_ERROR_CHECK(esp_wifi_start());
-    return ESP_OK;
-}
-
-static esp_err_t get_ap_ip(char *out_ip, size_t len)
-{
-    esp_netif_ip_info_t ip_info;
-    if (ap_netif == NULL) {
-        return ESP_ERR_INVALID_STATE;
-    }
-    ESP_ERROR_CHECK(esp_netif_get_ip_info(ap_netif, &ip_info));
-    inet_ntoa_r(ip_info.ip, out_ip, len);
-    return ESP_OK;
-}
-
-static esp_err_t root_get_handler(httpd_req_t *req)
-{
-    wifiLastActivity = xTaskGetTickCount();
-
-    char ip_str[16] = {0};
-    get_ap_ip(ip_str, sizeof(ip_str));
-
-    const char *nombreArchivo = (filename[0] == '/') ? filename + 1 : filename;
-
-    char html[1024];
-    snprintf(html, sizeof(html),
-        "<!DOCTYPE html><html><head><meta charset='UTF-8'><title>ESP32 GPS Logger</title>"
-        "<style>body{font-family:Arial;text-align:center;margin:50px;}h1{color:#333;} "
-        "a.button{background:#4CAF50;color:white;padding:20px 40px;text-decoration:none;"
-        "font-size:24px;border-radius:12px;display:inline-block;margin:20px;}</style></head>"
-        "<body><h1>GPS Logger</h1><p>Archivo listo para descargar:</p>"
-        "<a href='/download' class='button' download='%s'>Descargar %s</a>"
-        "<hr><p>IP: %s</p><p>Se apagará en 5 min sin uso.</p></body></html>",
-        nombreArchivo, nombreArchivo, ip_str);
+    esp_err_t err = esp_pm_configure(&pm_config);
 
-    httpd_resp_set_type(req, "text/html");
-    return httpd_resp_send(req, html, HTTPD_RESP_USE_STRLEN);
-}
-
-static esp_err_t download_get_handler(httpd_req_t *req)
-{
-    wifiLastActivity = xTaskGetTickCount();
-
-    struct stat st;
-    if (stat(filename, &st) != 0) {
-        httpd_resp_send_404(req);
-        return ESP_FAIL;
-    }
-
-    FILE *file = fopen(filename, "r");
-    if (!file) {
-        httpd_resp_send_404(req);
-        return ESP_FAIL;
+    if (err != ESP_OK) {
+        ESP_LOGE("General", "Error configuring power management");
     }
 
-    const char *nombreArchivo = (filename[0] == '/') ? filename + 1 : filename;
-    char disposition[128];
-    snprintf(disposition, sizeof(disposition),
-             "attachment; filename=\"%s\"", nombreArchivo);
-
-    httpd_resp_set_type(req, "application/gpx+xml");
-    httpd_resp_set_hdr(req, "Content-Disposition", disposition);
-    httpd_resp_send_file(req, file, st.st_size);
+    ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_NONE)); // Desactiva ahorro de energía WiFi
 
-    fclose(file);
-    return ESP_OK;
+    vTaskSuspend(medicionesHandle); //inicia suspendida
 }
 
-static const httpd_uri_t root_uri = {
-    .uri       = "/",
-    .method    = HTTP_GET,
-    .handler   = root_get_handler,
-    .user_ctx  = NULL
-};
-
-static const httpd_uri_t download_uri = {
-    .uri       = "/download",
-    .method    = HTTP_GET,
-    .handler   = download_get_handler,
-    .user_ctx  = NULL
-};
-
-static esp_err_t iniciar_servidor_http(void)
-{
-    httpd_config_t config = HTTPD_DEFAULT_CONFIG();
-    if (httpd_start(&http_server, &config) != ESP_OK) {
-        return ESP_FAIL;
-    }
-
-    httpd_register_uri_handler(http_server, &root_uri);
-    httpd_register_uri_handler(http_server, &download_uri);
-    return ESP_OK;
-}