main.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. #include <stdio.h>
  2. #include "freertos/FreeRTOS.h"
  3. #include "freertos/task.h"
  4. #include "driver/gpio.h"
  5. #include "esp_rom_sys.h"
  6. #include "esp_log.h"
  7. #include "dht22.h"
  8. #include "GPS_parser.h"
  9. #include "driver/uart.h"
  10. #include <string.h>
  11. #include <sys/unistd.h>
  12. #include <sys/stat.h>
  13. #include "esp_vfs_fat.h"
  14. #include "sdmmc_cmd.h"
  15. #include "ssd1306.h"
  16. #include <driver/i2c_master.h>
  17. const char *DHT_TAG = "DHT22";
  18. const char *GPS_TAG = "GPS_PARSER";
  19. const char *SD_TAG = "SD_CARD";
  20. const char *OLED_TAG = "SSD1306OLED";
  21. #define MOUNT_POINT "/sdcard"
  22. #define PIN_NUM_MISO CONFIG_PIN_MISO
  23. #define PIN_NUM_MOSI CONFIG_PIN_MOSI
  24. #define PIN_NUM_CLK CONFIG_PIN_CLK
  25. #define PIN_NUM_CS CONFIG_PIN_CS
  26. #define PIN_NUM_SDA CONFIG_PIN_SDA
  27. #define PIN_NUM_SCL CONFIG_PIN_SCL
  28. //definicion de tiempos de pulsacion
  29. #define PULSACION_LARGA_MS 2000
  30. #define DURACION_WATCHDOG_MS 10000
  31. #define MEASUREMENT_INTERVAL_S 1
  32. const int uart_buffer_size = (1024 * 2);
  33. int length = 0;
  34. uint8_t data;
  35. static gps_parser_t gps;
  36. void uart_configurator();
  37. static esp_err_t s_example_write_file(const char *path, char *data);
  38. static i2c_master_bus_handle_t i2c_bus0_init(gpio_num_t sda, gpio_num_t scl, uint32_t hz);
  39. struct SensorData {
  40. double latitude;
  41. double longitude;
  42. float altura;
  43. char tiempo;
  44. float velocidad;
  45. float temperature;
  46. float humidity;
  47. float pressure;
  48. };
  49. struct SensorData latestData;
  50. struct SensorData datosAntiguos;
  51. SemaphoreHandle_t dataMutex; // Mutex para proteger el acceso a latestData
  52. SemaphoreHandle_t buttonSemaphore; // Semáforo para la tarea del botón
  53. bool grabando = false; //inicia apagado
  54. bool finalizado = true; //indica que no hay ninguna grabacion ni iniciada ni pausada
  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] = "/panchas.gpx";
  61. ssd1306_handle_t d = NULL;
  62. void OLED_test(){
  63. i2c_master_bus_handle_t i2c_bus =
  64. i2c_bus0_init(PIN_NUM_SDA, PIN_NUM_SCL, 400000);
  65. ssd1306_config_t cfg = {
  66. .width = 128,
  67. .height = 64,
  68. .fb = NULL, // let driver allocate internally
  69. .fb_len = 0,
  70. .iface.i2c =
  71. {
  72. .port = I2C_NUM_0,
  73. .addr = 0x3C, // typical SSD1306 I2C address
  74. .rst_gpio = GPIO_NUM_NC, // no reset pin
  75. },
  76. };
  77. ESP_ERROR_CHECK(ssd1306_new_i2c(&cfg, &d));
  78. ESP_ERROR_CHECK(ssd1306_clear(d));
  79. ESP_ERROR_CHECK(ssd1306_draw_rect(d, cfg.width / 2 - 50, cfg.height / 2 - 10, 100, 20, false));
  80. ESP_ERROR_CHECK(ssd1306_display(d));
  81. ESP_ERROR_CHECK(ssd1306_draw_circle(d, cfg.width / 2, cfg.height / 2, 20, true));
  82. ESP_ERROR_CHECK(ssd1306_display(d));
  83. ESP_ERROR_CHECK(ssd1306_draw_text_scaled(d, 0, 0, "Iniciando...", true, ));
  84. ESP_ERROR_CHECK(ssd1306_display(d));
  85. vTaskDelay(pdMS_TO_TICKS(1000));
  86. }
  87. void OLED_print(const char& line1, const char& line2){
  88. ESP_ERROR_CHECK(ssd1306_clear(d));
  89. ESP_ERROR_CHECK(ssd1306_draw_text_scaled(d, 0, 0, line1, true, 2));
  90. ESP_ERROR_CHECK(ssd1306_draw_text_scaled(d, 0, 40, line2, true, 2));
  91. ESP_ERROR_CHECK(ssd1306_display(d));
  92. }
  93. void DHT_test (){
  94. float t;
  95. float h;
  96. static esp_err_t err = dht_attach_pin();
  97. if (err != ESP_OK) {
  98. OLED_print("DHT22", "Error");
  99. ESP_LOGE(DHT_TAG, "Failed to attach DHT pin: %s", esp_err_to_name(err));
  100. vTaskDelay(pdMS_TO_TICKS(5000)); // Wait for 5 seconds before retrying
  101. DHT_test(); //Reintentar
  102. }
  103. err = dht_read(&t, &h);
  104. if (err != ESP_OK) {
  105. OLED_print("DHT22", "Error");
  106. ESP_LOGE(DHT_TAG, "Failed to read DHT : %s", esp_err_to_name(err));
  107. vTaskDelay(pdMS_TO_TICKS(5000)); // Wait for 5 seconds before retrying
  108. DHT_test(); //Reintentar
  109. }
  110. else OLED_print("DHT22", "Correcto");
  111. }
  112. void SD_test(){
  113. }
  114. void app_main(void)
  115. {
  116. // Initialize DHT22 sensor
  117. /*
  118. float temperature;
  119. float humidity;
  120. esp_err_t err = dht_attach_pin();
  121. if (err != ESP_OK) {
  122. ESP_LOGE(DHT_TAG, "Failed to attach DHT pin: %s", esp_err_to_name(err));
  123. vTaskDelay(pdMS_TO_TICKS(5000)); // Wait for 5 seconds before retrying
  124. return;
  125. }
  126. vTaskDelay(pdMS_TO_TICKS(2000)); // Wait for 2 seconds before starting the main loop
  127. while (1) {
  128. if (dht_read(&temperature, &humidity) == ESP_OK) {
  129. ESP_LOGI(DHT_TAG, "Temperature: %.1f°C, Humidity: %.1f%%", temperature, humidity);
  130. } else {
  131. ESP_LOGE(DHT_TAG, "Failed to read from DHT22 sensor");
  132. }
  133. vTaskDelay(pdMS_TO_TICKS(5000)); // Wait for 5 seconds before the next reading
  134. }
  135. */
  136. // Initialize GPS parser
  137. /*
  138. uart_configurator();
  139. double latitude, longitude;
  140. gps_parser_init(&gps);
  141. while(1){
  142. while (uart_read_bytes(UART_NUM_2, &data, 1, 0)){
  143. gps_parser_encode(&gps, data);
  144. }
  145. if (gps_location_is_valid(&gps.location)) {
  146. double lat = gps_location_lat(&gps.location);
  147. double lng = gps_location_lng(&gps.location);
  148. ESP_LOGI(GPS_TAG, "Lat: %.8f, Lng: %.8f", lat, lng);
  149. }
  150. if (gps_date_is_valid(&gps.date) && gps_time_is_valid(&gps.time)) {
  151. ESP_LOGI(GPS_TAG, "Fecha: %02u/%02u/%04u Hora: %02u:%02u:%02u\n",
  152. gps_date_day(&gps.date),
  153. gps_date_month(&gps.date),
  154. gps_date_year(&gps.date),
  155. gps_time_hour(&gps.time),
  156. gps_time_minute(&gps.time),
  157. gps_time_second(&gps.time));
  158. }
  159. vTaskDelay(pdMS_TO_TICKS(2000)); // Wait for 1 second before the next reading
  160. }
  161. */
  162. // Initialize SD card
  163. /*
  164. esp_vfs_fat_sdmmc_mount_config_t mount_config = {
  165. .format_if_mount_failed = false,
  166. .max_files = 5,
  167. .allocation_unit_size = 16 * 1024
  168. };
  169. sdmmc_card_t *card;
  170. const char mount_point[] = MOUNT_POINT;
  171. sdmmc_host_t host = SDSPI_HOST_DEFAULT();
  172. host.max_freq_khz = 9000; //a mas freq no funciona, porque pipas
  173. spi_bus_config_t bus_cfg = {
  174. .mosi_io_num = PIN_NUM_MOSI,
  175. .miso_io_num = PIN_NUM_MISO,
  176. .sclk_io_num = PIN_NUM_CLK,
  177. .quadwp_io_num = -1,
  178. .quadhd_io_num = -1,
  179. .max_transfer_sz = 4092,
  180. };
  181. esp_err_t ret = spi_bus_initialize(host.slot, &bus_cfg, SDSPI_DEFAULT_DMA);
  182. if (ret != ESP_OK) {
  183. ESP_LOGE(SD_TAG, "Failed to initialize bus.");
  184. return;
  185. }
  186. sdspi_device_config_t slot_config = SDSPI_DEVICE_CONFIG_DEFAULT();
  187. slot_config.gpio_cs = PIN_NUM_CS;
  188. slot_config.host_id = host.slot;
  189. ESP_LOGI(SD_TAG, "Mounting filesystem");
  190. ret = esp_vfs_fat_sdspi_mount(mount_point, &host, &slot_config, &mount_config, &card);
  191. if (ret != ESP_OK) {
  192. if (ret == ESP_FAIL) {
  193. ESP_LOGE(SD_TAG, "Failed to mount filesystem. "
  194. "If you want the card to be formatted, set the CONFIG_EXAMPLE_FORMAT_IF_MOUNT_FAILED menuconfig option.");
  195. } else {
  196. ESP_LOGE(SD_TAG, "Failed to initialize the card (%s). "
  197. "Make sure SD card lines have pull-up resistors in place.", esp_err_to_name(ret));
  198. }
  199. return;
  200. }
  201. ESP_LOGI(SD_TAG, "Filesystem mounted");
  202. // Card has been initialized, print its properties
  203. sdmmc_card_print_info(stdout, card);
  204. const char *file_foo = MOUNT_POINT"/foo.txt";
  205. // Check if destination file exists before renaming
  206. struct stat st;
  207. if (stat(file_foo, &st) == 0) {
  208. // Delete it if it exists
  209. unlink(file_foo);
  210. }
  211. const char *file_nihao = MOUNT_POINT"/nihao.txt";
  212. // All done, unmount partition and disable SPI peripheral
  213. esp_vfs_fat_sdcard_unmount(mount_point, card);
  214. ESP_LOGI(SD_TAG, "Card unmounted");
  215. //deinitialize the bus after all devices are removed
  216. spi_bus_free(host.slot);
  217. */
  218. // Initialize display
  219. /*
  220. i2c_master_bus_handle_t i2c_bus =
  221. i2c_bus0_init(GPIO_NUM_21, GPIO_NUM_22, 400000);
  222. ssd1306_config_t cfg = {
  223. .width = 128,
  224. .height = 64,
  225. .fb = NULL, // let driver allocate internally
  226. .fb_len = 0,
  227. .iface.i2c =
  228. {
  229. .port = I2C_NUM_0,
  230. .addr = 0x3C, // typical SSD1306 I2C address
  231. .rst_gpio = GPIO_NUM_NC, // no reset pin
  232. },
  233. };
  234. ssd1306_handle_t d = NULL;
  235. ESP_ERROR_CHECK(ssd1306_new_i2c(&cfg, &d));
  236. // ----- Clear screen -----
  237. ESP_ERROR_CHECK(ssd1306_clear(d));
  238. // ----- Draw pixels in corners of screen -----
  239. ESP_ERROR_CHECK(ssd1306_draw_pixel(d, 0, 0, true));
  240. ESP_ERROR_CHECK(ssd1306_draw_pixel(d, cfg.width - 1, 0, true));
  241. ESP_ERROR_CHECK(ssd1306_draw_pixel(d, 0, cfg.height - 1, true));
  242. ESP_ERROR_CHECK(ssd1306_draw_pixel(d, cfg.width - 1, cfg.height - 1, true));
  243. // ----- Draw rectangles -----
  244. ESP_ERROR_CHECK(ssd1306_draw_rect(d, 2, 2, 40, 20, false));
  245. ESP_ERROR_CHECK(ssd1306_draw_rect(d, 2, 24, 32, 16, true));
  246. // ----- Draw circles -----
  247. ESP_ERROR_CHECK(ssd1306_draw_circle(d, 32, 52, 8, true));
  248. ESP_ERROR_CHECK(ssd1306_draw_circle(d, 100, 52, 4, false));
  249. // ----- Draw lines -----
  250. ESP_ERROR_CHECK(ssd1306_draw_line(d, 2, 2, 40, 20, true));
  251. ESP_ERROR_CHECK(ssd1306_draw_line(d, 32, 52, 100, 52, true));
  252. // ----- Draw text -----
  253. ESP_ERROR_CHECK(ssd1306_draw_text(d, 48, 2, "OK!", true));
  254. ESP_ERROR_CHECK(
  255. ssd1306_draw_text_scaled(d, 48, 10, "Hello\nWorld!", true, 2));
  256. ESP_ERROR_CHECK(ssd1306_display(d));
  257. ESP_LOGI(OLED_TAG, "Display updated successfully.");
  258. */
  259. }
  260. void uart_configurator() {
  261. // Configure UART parameters
  262. uart_config_t uart_config = {
  263. .baud_rate = 115200,
  264. .data_bits = UART_DATA_8_BITS,
  265. .parity = UART_PARITY_DISABLE,
  266. .stop_bits = UART_STOP_BITS_1,
  267. .flow_ctrl = UART_HW_FLOWCTRL_DISABLE
  268. };
  269. QueueHandle_t uart_queue;
  270. // Install UART driver using an event queue here
  271. ESP_ERROR_CHECK(uart_driver_install(UART_NUM_2, uart_buffer_size, uart_buffer_size, 10, &uart_queue, 0));
  272. ESP_ERROR_CHECK(uart_param_config(UART_NUM_2, &uart_config));
  273. ESP_ERROR_CHECK(uart_set_pin(UART_NUM_2, GPIO_NUM_17, GPIO_NUM_16, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE));
  274. }
  275. static esp_err_t s_example_write_file(const char *path, char *data)
  276. {
  277. ESP_LOGI(SD_TAG, "Opening file %s", path);
  278. FILE *f = fopen(path, "w");
  279. if (f == NULL) {
  280. ESP_LOGE(SD_TAG, "Failed to open file for writing");
  281. return ESP_FAIL;
  282. }
  283. fprintf(f, data);
  284. fclose(f);
  285. ESP_LOGI(SD_TAG, "File written");
  286. return ESP_OK;
  287. }
  288. // Init i2c
  289. static i2c_master_bus_handle_t i2c_bus0_init(gpio_num_t sda, gpio_num_t scl, uint32_t hz) {
  290. i2c_master_bus_config_t bus_cfg = {
  291. .i2c_port = I2C_NUM_0,
  292. .sda_io_num = sda,
  293. .scl_io_num = scl,
  294. .clk_source = I2C_CLK_SRC_DEFAULT,
  295. .glitch_ignore_cnt = 0,
  296. .flags.enable_internal_pullup = true,
  297. };
  298. i2c_master_bus_handle_t bus = NULL;
  299. ESP_ERROR_CHECK(i2c_new_master_bus(&bus_cfg, &bus));
  300. // NOTE: per-device speed is set when adding the device (in driver bind).
  301. return bus;
  302. }