main.ino 16 KB

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