main.ino 17 KB

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