problem with SD writing, random failure slows down and samples are lost

hi, have a nice day, I am continuing the project of a colleague. I have adapted it to my needs:
I am sampling an analog signal at 360 Hz, to transmit it by Serial Tx, Bluetooth, and SD recording with LED indicators to indicate Transmit / Stop status.
With the Tx Serial and Bluetooth I have no problem.

But with micro SD recording, I read that you can have problems generated by the writing time (latency), the code works well. The sampling of the analog signal is stable, but completely random (2-5 times per hour) 1 or 2 cycles the interruptions become slow and samples of the analog signal are lost. I have recorded continuously up to 12 hours and the behavior is exactly the same in the 1st hour as in the 12th.

Any ideas to correct the problem? I thank you in advance for your comments and contributions.

#include <RTClib.h>
RTC_DS1307 RTC;
#include <SoftwareSerial.h>
#include <TimerOne.h>
SoftwareSerial BT(8,9);//RX,TX
#include <SPI.h>
#include <SD.h>
File myFile;
#include <Wire.h>
byte year, month, date, DoW, hour, minute, second;
char linea[15];
char voltaje[4];

// --- Mapeamento de Hardware ---
#define butDown 7
#define butP    5
#define butM    6
#define LED1    A1
#define LED2    A2
#define CS      10
#define LED3    4
#define LED4    3
#define LED5    2
#define LED6    A3

// Funciones  Menu
void changeMenu();
void dispMenu();
void Modo1();
void Modo2();
void Modo3();
void menu4();

// Variables Globales
char menu = 0x01;  //Variable para seleccionar el menú
char set1 = 0x00; //Control de los LEDS
boolean t_butDown, t_butP, t_butM; //Banderas para almacenar el estado de los botones

void setup()
{ Wire.begin();
 RTC.begin();
  pinMode(7, INPUT_PULLUP);
  pinMode(5, INPUT_PULLUP);
  pinMode(6, INPUT_PULLUP);
  
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT); 
  pinMode(CS, OUTPUT);
  pinMode(LED3, OUTPUT);
  pinMode(LED4, OUTPUT); 
  pinMode(LED5, OUTPUT);
  pinMode(LED6, OUTPUT); 
  
  t_butDown = 0x00;
  t_butP    = 0x00;
  t_butM    = 0x00;
  }

void loop()
{changeMenu();
 dispMenu();
 getTime(&year, &month, &date, &DoW, &hour, &minute, &second);
}

void getTime(byte* year, byte* month, byte* date, byte* DoW, byte* hour, byte* minute, byte* second) {
  DateTime now = RTC.now();
  //if (!now) return; 
  *year = now.year()- 2000;
  *month = now.month();
  *date = now.day();
  *DoW = now.dayOfWeek();
  *hour = now.hour();
  *minute = now.minute();
  *second = now.second();
}

//FN del menu
void changeMenu()
{
if(!digitalRead(butDown)) t_butDown = 0x01;
if(digitalRead(butDown) && t_butDown)
{ t_butDown = 0x00;
 menu++;
      
if(menu > 0x04) menu = 0x01;
}
}

void dispMenu()
{
switch(menu)
{
case 0x01:
Modo1();
digitalWrite(LED3, HIGH);
digitalWrite(LED4, LOW);
digitalWrite(LED5, LOW);
digitalWrite(LED6, LOW);
break;
case 0x02:
Modo2();
   getTime(&year, &month, &date, &DoW, &hour, &minute, &second);
digitalWrite(LED3, LOW);
digitalWrite(LED4, HIGH);
digitalWrite(LED5, LOW);
digitalWrite(LED6, LOW);
break;
case 0x03:
Modo3();
digitalWrite(LED3, LOW);
digitalWrite(LED4, LOW);
digitalWrite(LED5, HIGH);
digitalWrite(LED6, LOW);
break;
case 0x04:
Modo4();
digitalWrite(LED3, LOW);
digitalWrite(LED4, LOW);
digitalWrite(LED5, LOW);
digitalWrite(LED6, HIGH);
break; 
} 
}

void Modo1() //Modo 1 Serial port
{
if(!digitalRead(butP))    t_butP    = 0x01; 
if(!digitalRead(butM))    t_butM    = 0x01;   
if(digitalRead(butP) && t_butP)
{                                                    
t_butP = 0x00;
Puertoserie();
digitalWrite(LED1, HIGH); 
digitalWrite(LED2, LOW);          
}
   if(digitalRead(butM) && t_butM)
{                                                    
t_butM = 0x00;
Serial.end();
digitalWrite(LED1, LOW);
digitalWrite(LED2, HIGH);
delay(1500);
digitalWrite(LED2, LOW);
}
}

void Modo2()  //Modo 2 SD card 
{
if(!digitalRead(butP))    t_butP    = 0x01;
 if(!digitalRead(butM))    t_butM    = 0x01; 
 if(digitalRead(butP) && t_butP)
 {   
    if (!SD.begin(CS))
  {}                                                 
 t_butP = 0x00;
   set1++;
   
      if(set1 > 2) set1 = 0x01;
      
      switch(set1)
      {
          case 0x01:
digitalWrite(LED1, LOW);
digitalWrite(LED2, LOW);
myFile = SD.open("datalog1.txt", FILE_WRITE);
getTime(&year, &month, &date, &DoW, &hour, &minute, &second);
myFile.write(linea, sprintf(linea, "Iniciado el %02d/%02d/20%02d, a las %02d:%02d:%02d\r\n", date, month, year, hour, minute, second));
 break;

case 0x02:
Timer1.initialize(2777); 
Timer1.attachInterrupt (timerIsr2);
 digitalWrite(LED1, HIGH);
 digitalWrite(LED2, LOW);
 }
 }
  
  if(digitalRead(butM) && t_butM)
   {
    Timer1.detachInterrupt();
  t_butM = 0x00;
  getTime(&year, &month, &date, &DoW, &hour, &minute, &second);
  myFile.write(linea, sprintf(linea, "Finalizado el %02d/%02d/20%02d, a las %02d:%02d:%02d\r\n", date, month, year, hour, minute, second)); // Pie
  myFile.close();
digitalWrite(LED1, LOW);
digitalWrite(LED2, HIGH);
delay(1500);
digitalWrite(LED2, LOW);
}
}
 
void Modo3()  //Modo 3 cel Bluetooth
{
if(!digitalRead(butP))    t_butP    = 0x01; 
if(!digitalRead(butM))    t_butM    = 0x01; 

if(digitalRead(butP) && t_butP) 
{                                                    
t_butP = 0x00; 
BluetoothCel();
digitalWrite(LED1, HIGH); 
digitalWrite(LED2, LOW);
} //end butP
   
if(digitalRead(butM) && t_butM) 
{                                                    
t_butM = 0x00; 
BT0CEL();
digitalWrite(LED1, LOW); 
digitalWrite(LED2, HIGH);  
delay(1500);
digitalWrite(LED2, LOW); 
}
}

void Modo4() //Transmision Bluetooth PC
{
  if(!digitalRead(butP))    t_butP    = 0x01;  
 if(!digitalRead(butM))    t_butM    = 0x01; 
  
 if(digitalRead(butP) && t_butP) 
 {                                                    
 t_butP = 0x00;
 BluetoothPC(); 
 digitalWrite(LED1, HIGH);
 digitalWrite(LED2, LOW);
 } //end butP
   
if(digitalRead(butM) && t_butM)  
{                                                    
 t_butM = 0x00;
 BT0PC();
 digitalWrite(LED1, LOW); 
 digitalWrite(LED2, HIGH);
 delay(1500);  
 digitalWrite(LED2, LOW); 
} //end butM
} //end Modo4

void Puertoserie() {
  Serial.begin(115200);
Timer1.initialize(2777); 
Timer1.attachInterrupt (timerIsr); 
}
void timerIsr()
{volatile int sensor= analogRead(A0);
Serial.println(sensor);// para ver en serial plotter
//Serial.print("v");//usar si que quiere graficar en LABVIEW
}

void timerIsr2()
{
   dtostrf(analogRead(A0) * 1, 1, 0, voltaje); 
   myFile.write(linea, sprintf(linea, "%s\t%02d:%02d:%02d\r\n", voltaje, hour, minute, second));//(SIN FECHA)
   // myFile.write(linea, sprintf(linea, "%s\t%02d/%02d/20%02d\t%02d:%02d:%02d\r\n", voltaje, date, month, year, hour, minute, second));// con fecha
  }

void BluetoothCel() {
BT.begin(115200);
Timer1.initialize(2777); 
Timer1.attachInterrupt (timerIsr1); 
  }
void timerIsr1()
{
volatile int sensor= analogRead(A0);
BT.print("E");
BT.print(sensor);
}

void BluetoothPC(){
BT.begin(115200);
Timer1.initialize(2777);
Timer1.attachInterrupt (timerIsr3);
}
void timerIsr3()
{ volatile int sensor= analogRead(A0);
BT.print("v"); 
BT.print(sensor);
}

void BT0PC(){
BT.begin(115200);
Timer1.initialize(2777); 
Timer1.attachInterrupt (timerIsr4);
}
//Rutina de interrupcion
void timerIsr4()
{ volatile int sensor=0; 
BT.print("v"); 
BT.print(sensor);
}

void BT0CEL(){
BT.begin(115200);
Timer1.initialize(2777); 
Timer1.attachInterrupt (timerIsr5); 
}
void timerIsr5()
{ volatile int sensor=0;
BT.print("E");
BT.println(sensor);
}

codigo.ino (6.47 KB)

do you have the CS pin of the SD module connected to pin 10?

SD library uses a memory cache/buffer. Default size of the buffer is 512 bytes. Could it be that the buffer overflows because the card can't write so fast?

I try to read your code. Doesn't it call SD.begin() in every loop?

yes,why did him do "SD.begin()" in every loop ?