fix(sd): resolver conflicto de pines SPI con CAN y crear archivo de sesion por arranque

La SD usaba VSPI por defecto (SCK=18, MISO=19, MOSI=23, CS=5), y el pin
MOSI (GPIO23) coincidía físicamente con el RX del CAN, por lo que ambos
periféricos competían por el mismo pin y la SD no funcionaba de forma
fiable.

Se migra la SD a un bus SPI propio (HSPI) con los pines validados por
esquemático de la PCB (CS=25, MOSI=26, SCK=27, MISO=14), que no
colisionan con ningún pin usado por el CAN. Se baja además la
velocidad de reloj SPI de 20 MHz a 1 MHz mediante SdSpiConfig,
necesario por la integridad de señal del cableado/PCB actual.

Se añade también la creación de un archivo de sesión nuevo en cada
arranque (G26-1.csv, G26-2.csv, ...) usando O_EXCL para no sobrescribir
nunca sesiones anteriores, evitando que distintas ejecuciones
compartan el mismo archivo con timestamps solapados.
This commit is contained in:
Alejandro Guerrero 2026-07-21 20:02:00 +02:00
parent 72dc48807d
commit ad23f59ba4
5 changed files with 49 additions and 29 deletions

View file

@ -6,9 +6,15 @@
#include "include/data_processor.hpp" #include "include/data_processor.hpp"
// --- CONFIGURACIÓN SD (VSPI) --- // --- CONFIGURACIÓN SD (HSPI, pines de la PCB validados por esquemático) ---
#define SD_CS_PIN 5 #define SD_CS 25
#define SPI_CLOCK SD_SCK_MHZ(20) #define SD_MOSI 26
#define SD_SCK 27
#define SD_MISO 14
SPIClass spiSD(HSPI);
#define SD_CONFIG SdSpiConfig(SD_CS, DEDICATED_SPI, SD_SCK_MHZ(1), &spiSD)
SdFat sd; SdFat sd;
SdFile logFile; SdFile logFile;
@ -22,38 +28,44 @@ void setup() {
Serial.println("\n--- G26 TELEMETRY: INICIO DE SISTEMA ---"); Serial.println("\n--- G26 TELEMETRY: INICIO DE SISTEMA ---");
// 1. INICIALIZACIÓN SD // 1. INICIALIZACIÓN SD
if (!sd.begin(SD_CS_PIN, SPI_CLOCK)) { spiSD.begin(SD_SCK, SD_MISO, SD_MOSI, SD_CS);
if (!sd.begin(SD_CONFIG)) {
Serial.println("[FALLO] SD no detectada. El sistema continuará sin Datalogging."); Serial.println("[FALLO] SD no detectada. El sistema continuará sin Datalogging.");
} else { } else {
if (logFile.open("G26.csv", O_RDWR | O_CREAT | O_APPEND)) { char filename[24];
int session = 1;
bool opened = false;
// Si el archivo es nuevo (tamaño 0), escribimos la cabecera while (!opened && session < 100000) {
if (logFile.fileSize() == 0) { snprintf(filename, sizeof(filename), "G26-%d.csv", session);
logFile.println("Time,ECT"); if (logFile.open(filename, O_RDWR | O_CREAT | O_EXCL)) {
logFile.sync(); opened = true;
Serial.printf("[OK] Nueva sesion: %s\n", filename);
} else {
session++;
}
} }
// El archivo se queda abierto y listo. if (opened) {
Serial.println("[OK] Archivo abierto"); logFile.println("Time,ECT,RPM,TPS,VBATT");
logFile.sync();
} else { } else {
Serial.println("[ERROR] No se pudo abrir el archivo G26.csv"); Serial.println("[ERROR] No se pudo abrir archivo de sesion");
} }
} }
// 2. VINCULACIÓN // 2. VINCULACIÓN
// Le damos al procesador acceso a la SD para que guarde cuando lleguen datos
processor.setLogSystem(&sd, &logFile); processor.setLogSystem(&sd, &logFile);
can_interface.set_data_proccessor(&processor); can_interface.set_data_proccessor(&processor);
// 3. INICIO CAN // 3. INICIO CAN
can_interface.start(); can_interface.start();
can_interface.start_listening_task(); // Escucha en Core 1 (Background) can_interface.start_listening_task();
Serial.println("[OK] Sistema ONLINE."); Serial.println("[OK] Sistema ONLINE.");
} }
void loop() { void loop() {
delay(100);
delay(100); }
}

View file

@ -1,8 +1,8 @@
#ifndef CAN_HPP #ifndef CAN_HPP
#define CAN_HPP #define CAN_HPP
#define RX_PIN 13 #define RX_PIN 23
#define TX_PIN 38 #define TX_PIN 22
#define POLLING_RATE_MS 1000 #define POLLING_RATE_MS 1000
#define TRANSMIT_RATE_MS 1000 #define TRANSMIT_RATE_MS 1000

View file

@ -9,7 +9,11 @@ public:
// Estructura de datos // Estructura de datos
struct CarState { struct CarState {
int ect = 0; // Temperatura (IMPORTANTE POR AHORA). Luego habría que añadir aquí todas las variables que se vallan a guardar. int ect = 0;
int rpm = 0;
int tps = 0;
double vbatt = 0;
}; };
// Configuración SD // Configuración SD

View file

@ -11,7 +11,7 @@ static bool driver_installed = false;
void CAN::start() { void CAN::start() {
Serial.println("Starting CAN Controller..."); Serial.println("Starting CAN Controller...");
twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT((gpio_num_t)TX_PIN, (gpio_num_t)RX_PIN, TWAI_MODE_NORMAL); twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT((gpio_num_t)TX_PIN, (gpio_num_t)RX_PIN, TWAI_MODE_NORMAL);
twai_timing_config_t t_config = TWAI_TIMING_CONFIG_125KBITS(); twai_timing_config_t t_config = TWAI_TIMING_CONFIG_500KBITS();
twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL(); twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL();
esp_err_t install_status = twai_driver_install(&g_config, &t_config, &f_config); esp_err_t install_status = twai_driver_install(&g_config, &t_config, &f_config);

View file

@ -6,10 +6,14 @@ void DataProcessor::send_serial_frame_0(int rpmh, int rpml, int tpsh, int tpsl,
car.ect = ect; // GUARDAR LA VARIABLE DEL FRAME EN LA ESTRUCTURA car.ect = ect; // GUARDAR LA VARIABLE DEL FRAME EN LA ESTRUCTURA
// El resto de variables no son relevantes ahora, se quedan comentadas para ahorrar memoria int rpm = (rpmh * 256) + rpml;
// int rpm = (rpmh * 256) + rpml; car.rpm = rpm;
// int tps = (tpsh * 256) + tpsl;
// double vbatt = ((vbatth * 256) + vbattl) / 100.0; int tps = (tpsh * 256) + tpsl;
car.tps = tps;
double vbatt = ((vbatth * 256) + vbattl) / 100.0;
car.vbatt = vbatt;
// 2. Escribimos en la SD // 2. Escribimos en la SD
flushToSD(); flushToSD();