main.ino 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. #include "TinyGPSPlus.h"
  2. #include "DHT.h"
  3. #include <Wire.h>
  4. #include <Adafruit_GFX.h>
  5. #include <Adafruit_SSD1306.h>
  6. #include "FS.h"
  7. #include "SD.h"
  8. #include "SPI.h"
  9. #include "Arduino.h"
  10. #include "math.h"
  11. #include "WiFi.h"
  12. #include "WebServer.h"
  13. #include "esp_pm.h"
  14. #include "esp_sleep.h"
  15. /*
  16. Uncomment and set up if you want to use custom pins for the SPI communication
  17. #define REASSIGN_PINS
  18. int sck = -1;
  19. int miso = -1;
  20. int mosi = -1;
  21. int cs = -1;
  22. */
  23. // Inicia I2C en pines default ESP32 (21 SDA, 22 SCL)
  24. #define SCREEN_WIDTH 128 // Ancho píxeles
  25. #define SCREEN_HEIGHT 64 // Alto píxeles
  26. #define OLED_RESET -1 // Reset pin (no usado)
  27. // Pines para UART2 (Serial2)
  28. #define RX_PIN 16 // RX del ESP32 conectado a TX del GPS
  29. #define TX_PIN 17 // TX del ESP32 conectado a RX del GPS
  30. #define GPS_BAUD 115200
  31. #define DHTPIN 4 // Digital pin connected to the DHT sensor
  32. #define DHTTYPE DHT22
  33. #define BUTTON_PIN 27 // pin para pulsador
  34. //definicion de tiempos de pulsacion
  35. #define PULASCION_LARGA_MS 2000
  36. #define DURACION_WATCHDOG_MS 10000
  37. #define MEASUREMENT_INTERVAL_S 1 //separación entre mediciones (s)
  38. #define DEG2RAD (M_PI/180.0)
  39. // Objeto TinyGPS++
  40. TinyGPSPlus gps;
  41. HardwareSerial gpsSerial(2); // Usar UART2
  42. DHT dht(DHTPIN, DHTTYPE);
  43. Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
  44. //valores de los sensores
  45. struct SensorData {
  46. double latitude = 0.0;
  47. double longitude = 0.0;
  48. float altura = 0.0;
  49. String tiempo = "";
  50. float velocidad = 0.0;
  51. float temperature = 0.0;
  52. float humidity = 0.0;
  53. float pressure = 0.0;
  54. };
  55. SensorData latestData;
  56. SensorData datosAntiguos;
  57. SemaphoreHandle_t dataMutex; // Mutex para proteger el acceso a latestData
  58. SemaphoreHandle_t buttonSemaphore; // Semáforo para la tarea del botón
  59. WebServer server(80);
  60. bool wifiActivado = false;
  61. unsigned long wifiLastActivity = 0;
  62. const unsigned long WIFI_TIMEOUT_MS = 300000; // 5 minutos
  63. const char* apSSID = "ESP32_GPS_Logger";
  64. const char* apPassword = "12345678";
  65. bool grabando = false; //inicia apagado
  66. bool finalizado = true; //indica que no hay ninguna grabacion ni iniciada ni pausada
  67. TaskHandle_t medicionesHandle = NULL; //para suspend/resume
  68. int pantallaEstado_grab = -1; //maquina de estados cuando se graba ruta
  69. int pantallaEstado_menu = -1; //maquina de estados cuando no se esta grabando ruta
  70. float distancia_total = 0.0;
  71. volatile unsigned long ignore_isr_until = 0; //para debounce
  72. char filename[13] = "/panchas.gpx";
  73. void OLED_print(const String& line1, const String& line2) {
  74. display.clearDisplay();
  75. display.setTextSize(2);
  76. display.setTextColor(SSD1306_WHITE);
  77. display.setCursor(0, 0);
  78. display.println(line1);
  79. display.println(line2);
  80. display.display();
  81. }
  82. void DHT_test() {
  83. dht.begin();
  84. float h = dht.readHumidity();
  85. float t = dht.readTemperature();
  86. if (isnan(h) || isnan(t)) {
  87. Serial.println("Failed to read from DHT sensor!");
  88. OLED_print("DHT22", "Error");
  89. delay(5000);
  90. DHT_test(); // Reintentar
  91. }
  92. else OLED_print("DHT22", "Correcto");
  93. }
  94. void OLED_test() { //pantallazo a blanco y luego iniciando
  95. // Inicia I2C en pines default ESP32 (21 SDA, 22 SCL)
  96. Wire.begin();
  97. if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Dirección común: 0x3C
  98. Serial.println(F("Error: OLED no encontrado!"));
  99. for (;;); // Para siempre
  100. }
  101. display.clearDisplay();
  102. display.fillScreen(SSD1306_WHITE); // Pantalla blanca
  103. delay(500);
  104. display.display();
  105. display.clearDisplay();
  106. display.setTextSize(2); // Tamaño texto
  107. display.setTextColor(SSD1306_WHITE);
  108. display.setCursor(0, 0); // Posición
  109. display.println("Iniciando...");
  110. display.display(); // Muestra
  111. delay(1000);
  112. }
  113. void SD_test(){
  114. if (!SD.begin()) {
  115. OLED_print("SD Card", "Error\nInserte");
  116. while (!SD.begin());
  117. OLED_print("SD Card", "Insertada");
  118. } else {
  119. OLED_print("SD Card", "Correcto");
  120. }
  121. uint8_t cardType = SD.cardType();
  122. if (cardType == CARD_NONE) {
  123. OLED_print("SD Card", "No detectada");
  124. while (cardType == CARD_NONE) {
  125. delay(1000);
  126. cardType = SD.cardType();
  127. }
  128. OLED_print("SD Card", "Detectada");
  129. }
  130. uint8_t cardSize = SD.cardSize() / (1024 * 1024);
  131. }
  132. void GPS_test_wait() {
  133. // Iniciar Serial2 para GPS
  134. bool fixObtained = false;
  135. gpsSerial.begin(GPS_BAUD, SERIAL_8N1, RX_PIN, TX_PIN);
  136. while (!fixObtained) {
  137. while (gpsSerial.available() > 0) {
  138. if (gps.encode(gpsSerial.read())) { // Procesa si hay sentencia NMEA completa
  139. if (gps.location.isValid() && gps.date.isValid() && gps.time.isValid()) {
  140. fixObtained = true;
  141. break;
  142. }
  143. }
  144. }
  145. delay(300);
  146. OLED_print("GPS", "Esperando");
  147. delay(300);
  148. OLED_print("GPS", "Esperando .");
  149. delay(300);
  150. OLED_print("GPS", "Esperando ..");
  151. delay(300);
  152. OLED_print("GPS", "Esperando ...");
  153. }
  154. OLED_print("GPS", "Encontrado");
  155. }
  156. float calcular_delta_dist(float lat1, float long1, float lat2, float long2){
  157. float R = 6371.0; // Radio de la Tierra en km
  158. float delta_lat = (lat2 - lat1) * DEG2RAD;
  159. float delta_long = (long2 - long1) * DEG2RAD;
  160. lat1 = lat1 * DEG2RAD;
  161. lat2 = lat2 * DEG2RAD;
  162. float a = sin(delta_lat/2)*sin(delta_lat/2)+cos(lat1)*cos(lat2)*sin(delta_long/2)*sin(delta_long/2);
  163. float c = 2 * atan2(sqrt(a),sqrt(1-a));
  164. return R * c; //En km
  165. }
  166. void task_mediciones(void *pvParameters) {
  167. TickType_t xLastWakeTime = xTaskGetTickCount();
  168. while(1) {
  169. unsigned long startMillis = millis();
  170. // se leen los valores antes de utilizar el semaphore
  171. while (gpsSerial.available() > 0) {
  172. char c = gpsSerial.read();
  173. Serial.print(c);
  174. }
  175. float new_latitude = gps.location.lat();
  176. float new_longitude = gps.location.lng();
  177. float new_altitude = gps.altitude.meters();
  178. String new_fecha = String(gps.date.year())+"-"+String(gps.date.month())+"-"+
  179. String(gps.date.day())+"T"+String(gps.time.hour())+":"+
  180. String(gps.time.minute())+":"+String(gps.time.second())+"."+
  181. String(gps.time.centisecond(),3);
  182. float new_speed = gps.speed.kmph();
  183. float new_temp = dht.readTemperature();
  184. float new_hum = dht.readHumidity();
  185. float new_press = 0.0; // Placeholder, no hay sensor de presión
  186. distancia_total += calcular_delta_dist(datosAntiguos.latitude, datosAntiguos.longitude, new_latitude, new_longitude);
  187. if (xSemaphoreTake(dataMutex, portMAX_DELAY) == pdTRUE) {
  188. latestData.latitude = new_latitude;
  189. latestData.longitude = new_longitude;
  190. latestData.altura = new_altitude;
  191. latestData.tiempo = new_fecha;
  192. latestData.velocidad = new_speed;
  193. latestData.temperature = new_temp;
  194. latestData.humidity = new_hum;
  195. latestData.pressure = new_press;
  196. datosAntiguos = latestData;
  197. xSemaphoreGive(dataMutex);
  198. }
  199. File file = SD.open(filename, FILE_APPEND);
  200. if (file) {
  201. //Crear la string para escribir en el archivo
  202. file.print(F("\t\t\t<trkpt lat=\""));
  203. file.print(datosAntiguos.latitude, 6);
  204. file.print(F("\" lon=\""));
  205. file.print(datosAntiguos.longitude, 6);
  206. file.println(F("\">"));
  207. file.print(F("\t\t\t\t<ele>"));
  208. file.print(datosAntiguos.altura);
  209. file.println(F("</ele>"));
  210. file.print(F("\t\t\t\t<time>"));
  211. file.print(datosAntiguos.tiempo);
  212. file.println(F("</time>"));
  213. file.print(F("\t\t\t\t<speed>"));
  214. file.print(datosAntiguos.velocidad);
  215. file.println(F("</speed>"));
  216. file.println(F("\t\t\t\t<extensions>"));
  217. file.println(F("\t\t\t\t\t<gpxtpx:TrackPointExtension>"));
  218. file.print(F("\t\t\t\t\t\t<gpxtpx:atemp>"));
  219. file.print(datosAntiguos.temperature);
  220. file.println(F("</gpxtpx:atemp>"));
  221. file.println(F("\t\t\t\t\t</gpxtpx:TrackPointExtension>"));
  222. file.print(F("\t\t\t\t\t<custom:humidity>"));
  223. file.print(datosAntiguos.humidity);
  224. file.println(F("</custom:humidity>"));
  225. file.print(F("\t\t\t\t\t<custom:pressure>"));
  226. file.print(datosAntiguos.pressure);
  227. file.println(F("</custom:pressure>"));
  228. file.println(F("\t\t\t\t</extensions>"));
  229. file.println(F("\t\t\t</trkpt>"));
  230. file.close();
  231. }
  232. unsigned long elapsedMillis = millis() - startMillis;
  233. Serial.println(elapsedMillis);
  234. vTaskDelayUntil(&xLastWakeTime, pdMS_TO_TICKS(MEASUREMENT_INTERVAL_S*1000)); // Espera x*1000 milisegundos
  235. }
  236. }
  237. void crear_archivo(){
  238. distancia_total = 0.0;
  239. int num = 1;
  240. sprintf(filename, "/data%03d.gpx", num);
  241. while (SD.exists(filename)) {
  242. num++;
  243. sprintf(filename, "/data%03d.gpx", num);
  244. }
  245. File file = SD.open(filename, FILE_WRITE);
  246. if (file) {
  247. file.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
  248. "<gpx creator=\"ESP32 GPS LOGGER\" version=\"1.1\"\n"
  249. "\txmlns=\"http://www.topografix.com/GPX/1/1\"\n"
  250. "\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
  251. "\txmlns:gpxtpx=\"http://www.garmin.com/xmlschemas/TrackPointExtension/v2\"\n"
  252. "\txmlns:gpxdata=\"http://www.cluetrust.com/XML/GPXDATA/1/0\"\n"
  253. "\txsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">\n"
  254. "\t<metadata>\n"
  255. "\t\t<name>Ruta grabada con ESP32 GPS Logger</name>\n"
  256. "\t\t<time>");
  257. file.print(String(gps.date.year()) + "-" + String(gps.date.month()) + "-" +
  258. String(gps.date.day()) + "T" + String(gps.time.hour()) + ":" +
  259. String(gps.time.minute()) + ":" + String(gps.time.second()) +
  260. "." + String(gps.time.centisecond()));
  261. file.println("</time>\n\t</metadata>\n"
  262. "\t<trk>\n"
  263. "\t\t<name>Rutita</name>\n"
  264. "\t\t<type>hiking</type>\n"
  265. "\t\t<trkseg>");
  266. file.close();
  267. } else {
  268. OLED_print("Error","creando archivo");
  269. delay(2000);
  270. }
  271. }
  272. void cerrar_archivo() {
  273. File file = SD.open(filename, FILE_APPEND);
  274. if (file){
  275. file.print("\t\t</trkseg>\n\t</trk>\n</gpx>");
  276. file.close();
  277. }
  278. //int num = 1;
  279. //sprintf(filename, "/data%03d.gpx", num);
  280. //while (SD.exists(filename)) {
  281. // num++;
  282. // sprintf(filename, "/data%03d.gpx", num);
  283. //}
  284. }
  285. void activarWiFi(){
  286. OLED_print("WiFi","Activando...");
  287. WiFi.mode(WIFI_AP);
  288. WiFi.softAP(apSSID, apPassword);
  289. IPAddress IP = WiFi.softAPIP();
  290. OLED_print("WiFi Activo", IP.toString());
  291. delay(2000);
  292. server.on("/", HTTP_GET, []() {
  293. wifiLastActivity = millis();
  294. String html = "<!DOCTYPE html><html><head><meta charset='UTF-8'><title>ESP32 GPS Logger</title>";
  295. html += "<style>body{font-family:Arial;text-align:center;margin:50px;}";
  296. html += "h1{color:#333;} a.button{background:#4CAF50;color:white;padding:20px 40px;";
  297. html += "text-decoration:none;font-size:24px;border-radius:12px;display:inline-block;margin:20px;}</style></head>";
  298. html += "<body><h1>GPS Logger</h1><p>Archivo listo para descargar:</p>";
  299. String nombreArchivo = String(filename).substring(1); // Ej. "data001.gpx"
  300. html += "<a href='/download' class='button' download='" + nombreArchivo + "'>Descargar " + nombreArchivo + "</a>";
  301. html += "<hr><p>IP: " + WiFi.softAPIP().toString() + "</p>";
  302. html += "<p>Se apagar&aacute; en 5 min sin uso.</p></body></html>";
  303. server.send(200, "text/html", html);
  304. });
  305. server.on("/download",HTTP_GET, []() {
  306. wifiLastActivity = millis();
  307. if (!SD.exists(filename)) {
  308. server.send(404, "text/plain", "Archivo no encontrado");
  309. return;
  310. }
  311. File file = SD.open(filename, FILE_READ);
  312. if (!file) {
  313. server.send(404, "text/plain", "Error al abrir el archivo");
  314. return;
  315. }
  316. String nombreArchivo = String(filename).substring(1); // Ej. "data001.gpx"
  317. server.sendHeader("Content-Disposition", "attachment; filename=\"" + nombreArchivo + "\"");
  318. server.streamFile(file, "application/gpx+xml");
  319. file.close();
  320. });
  321. server.begin();
  322. wifiActivado = true;
  323. wifiLastActivity = millis();
  324. }
  325. void desactivarWiFi(){
  326. server.stop();
  327. WiFi.softAPdisconnect(true);
  328. WiFi.mode(WIFI_OFF);
  329. wifiActivado = false;
  330. OLED_print("WiFi","Apagado");
  331. }
  332. void IRAM_ATTR isr_button() {
  333. unsigned long now = millis();
  334. if (now < ignore_isr_until) {
  335. return; // Ignorar interrupción si está dentro del período de debounce
  336. }
  337. static unsigned long lastInterrupt = 0;
  338. if ((now - lastInterrupt) > 300 ){ // debounce de 300 ms
  339. BaseType_t xHigherPriorityTaskWoken = pdFALSE;
  340. xSemaphoreGiveFromISR(buttonSemaphore, &xHigherPriorityTaskWoken);
  341. lastInterrupt = now;
  342. if (xHigherPriorityTaskWoken) {
  343. portYIELD_FROM_ISR();
  344. }
  345. }
  346. }
  347. void drawProgressBar(int x, int y, int w, int h, unsigned long progress, unsigned long total) {
  348. display.drawRect(x, y, w, h, SSD1306_WHITE); // Dibuja el borde
  349. int filledWidth = (progress * w) / total;
  350. display.fillRect(x + 1, y + 1, filledWidth - 2, h - 2, SSD1306_WHITE); // Dibuja la barra llena
  351. display.display();
  352. }
  353. void task_ui(void *pvParameters){
  354. unsigned long pressTime = 0;
  355. unsigned long lastActivity = millis();
  356. bool pantallaOn = true; //comprobar el estado inicial, no se cual sera
  357. bool processingButton = false;
  358. while(1){
  359. if (xSemaphoreTake(buttonSemaphore, pdMS_TO_TICKS(200)) == pdTRUE){ //button pressed
  360. if (processingButton) continue; //evita reentradas
  361. processingButton = true;
  362. pressTime = millis();
  363. lastActivity = millis(); //reset watchdog
  364. if (!pantallaOn){
  365. display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  366. pantallaOn = true;
  367. }
  368. bool timed_out = false;
  369. unsigned long checkTime = millis();
  370. while (digitalRead(BUTTON_PIN) == LOW){
  371. vTaskDelay(pdMS_TO_TICKS(10));
  372. checkTime = millis();
  373. if ((checkTime - pressTime) > DURACION_WATCHDOG_MS){ //10s timeout para evitar bloqueos
  374. timed_out = true;
  375. break;
  376. }
  377. drawProgressBar(0, SCREEN_HEIGHT - 10, SCREEN_WIDTH, 8, checkTime - pressTime, PULASCION_LARGA_MS);
  378. }
  379. ignore_isr_until = millis() + 500; //ignorar nuevas interrupciones durante 500 ms
  380. unsigned long duration = checkTime - pressTime;
  381. if (timed_out){
  382. OLED_print("Apagando","pantalla");
  383. display.ssd1306_command(SSD1306_DISPLAYOFF); //se apaga la
  384. pantallaOn = false;
  385. } else {
  386. if (grabando){
  387. if (duration >= PULASCION_LARGA_MS){
  388. grabando = false;
  389. vTaskSuspend(medicionesHandle);
  390. OLED_print("Ruta","pausada");
  391. } else {
  392. pantallaEstado_grab = (pantallaEstado_grab + 1) % 5; //cicla entre 0-4
  393. SensorData currentData;
  394. if(xSemaphoreTake(dataMutex, portMAX_DELAY) == pdTRUE){
  395. currentData = latestData;
  396. xSemaphoreGive(dataMutex);
  397. }
  398. switch (pantallaEstado_grab){
  399. case 0:
  400. OLED_print("Posicion",String(currentData.longitude) + "," + String(currentData.latitude));
  401. break;
  402. case 1:
  403. OLED_print("Distancia",String(distancia_total)+"km");
  404. break;
  405. case 2:
  406. OLED_print("Altitud",String(currentData.altura, 1)+"m");
  407. break;
  408. case 3:
  409. OLED_print("Temp/Hum",String(currentData.temperature,1)+"C/"+String(currentData.humidity,1)+"%");
  410. break;
  411. case 4:
  412. OLED_print("Velocidad",String(currentData.velocidad, 1)+"km/h");
  413. break;
  414. }
  415. }
  416. } else {
  417. if (duration >= PULASCION_LARGA_MS){
  418. switch (pantallaEstado_menu){
  419. case 0:
  420. //activar la ruta y crear el archivo
  421. crear_archivo();
  422. vTaskResume(medicionesHandle);
  423. OLED_print("Ruta","iniciada");
  424. finalizado = false;
  425. grabando = true;
  426. break;
  427. case 1:
  428. //cerrar el archivo y cambiar el valor de 'filename'
  429. cerrar_archivo();
  430. finalizado = true;
  431. break;
  432. case 2:
  433. //implementacion wifi
  434. if(!wifiActivado){
  435. activarWiFi();
  436. } else {
  437. desactivarWiFi();
  438. }
  439. break;
  440. }
  441. } else {
  442. pantallaEstado_menu = (pantallaEstado_menu + 1) % 3;
  443. int previous_state = -1;
  444. while (pantallaEstado_menu != previous_state) {
  445. previous_state = pantallaEstado_menu;
  446. switch (pantallaEstado_menu) {
  447. case 0:
  448. if (!finalizado) OLED_print("Reanudar","ruta");
  449. else OLED_print("Iniciar","ruta");
  450. break;
  451. case 1:
  452. if (SD.exists(filename) && !finalizado) {
  453. OLED_print("Finalizar","ruta");
  454. break;
  455. } else {
  456. pantallaEstado_menu = (pantallaEstado_menu + 1) % 3;
  457. }
  458. break;
  459. case 2:
  460. if (finalizado) {
  461. OLED_print("Conexion","WiFi");
  462. break;
  463. } else {
  464. pantallaEstado_menu = (pantallaEstado_menu + 1) % 3;
  465. }
  466. break;
  467. }
  468. }
  469. }
  470. }
  471. }
  472. lastActivity = millis(); //reset watchdog
  473. processingButton = false;
  474. vTaskDelay(pdMS_TO_TICKS(100)); //pequeño delay para no busy waiting
  475. }
  476. //check watchdog fuera del boton
  477. if (pantallaOn && ((millis() - lastActivity) > DURACION_WATCHDOG_MS)){
  478. display.ssd1306_command(SSD1306_DISPLAYOFF); //se apaga la pantalla
  479. pantallaOn = false;
  480. }
  481. //check wifi timeout
  482. if (wifiActivado){
  483. server.handleClient();
  484. if (WiFi.softAPgetStationNum() > 0){
  485. wifiLastActivity = millis(); //reset si hay clientes conectados
  486. }
  487. if ((millis() - wifiLastActivity) > WIFI_TIMEOUT_MS){
  488. desactivarWiFi();
  489. }
  490. }
  491. }
  492. }
  493. void setup() {
  494. Serial.begin(115200);
  495. pinMode(BUTTON_PIN, INPUT_PULLUP);
  496. attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), isr_button, FALLING);
  497. buttonSemaphore = xSemaphoreCreateBinary();
  498. dataMutex = xSemaphoreCreateMutex();
  499. // OLED check
  500. OLED_test();
  501. delay(1000);
  502. // DHT check
  503. DHT_test();
  504. delay(1000);
  505. // SD Card check
  506. SD_test();
  507. delay(1000);
  508. // GPS check
  509. // Enable RMC and VTG at 1 Hz
  510. gpsSerial.println("$PMTK314,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*29"); // Enables GGA, RMC, VTG
  511. gpsSerial.println("$PMTK220,1000*1F"); // Set update rate to 1 Hz (1000ms)
  512. delay(1000); // Give time to apply
  513. GPS_test_wait();
  514. delay(2000);
  515. // Crear tarea para mediciones
  516. xTaskCreatePinnedToCore(
  517. task_mediciones, // Función de la tarea
  518. "Mediciones", // Nombre de la tarea
  519. 8192, // Tamaño del stack
  520. NULL, // Parámetro de la tarea
  521. 10, // Prioridad de la tarea
  522. &medicionesHandle, // Handle de la tarea
  523. 0 // Núcleo donde se ejecuta
  524. );
  525. xTaskCreatePinnedToCore(
  526. task_ui, // Función de la tarea
  527. "UI", // Nombre de la tarea
  528. 8192, // Tamaño del stack
  529. NULL, // Parámetro de la tarea
  530. 5, // Prioridad de la tarea
  531. NULL, // Handle de la tarea
  532. 1 // Núcleo donde se ejecuta
  533. );
  534. esp_pm_config_esp32_t pm_config = {
  535. .max_freq_mhz = 240,
  536. .min_freq_mhz = 80,
  537. .light_sleep_enable = true
  538. };
  539. esp_err_t err = esp_pm_configure(&pm_config);
  540. if (err != ESP_OK) {
  541. Serial.println("Error configuring power management");
  542. }
  543. WiFi.setSleep(true); // Desactiva el modo de ahorro de energía del WiFi
  544. vTaskSuspend(medicionesHandle); //inicia suspendida
  545. }
  546. void loop() {
  547. vTaskDelete(NULL); // Deshabilita el loop
  548. }