unwanted deleys while logging to an SD card

Hello,

I need to log at a fast rate (every 1ms) data into a SD card and I get exactly every 10 cycles a delay because of the logging that varies between 3 - 55 ms.

Can you tell me if there is something I can do to reduce or eliminate this delay?
I am using an Arduino Due.

#include <SPI.h>
#include <SD.h>

int  pin=1;
long x_read =0,Z_read=0, Time=0;
String dataString;

void setup()
{
Serial.begin(115200);


   SD.begin(51);
}

void loop()
{  
File dataFile = SD.open("data6.txt",  O_CREAT | O_APPEND | O_WRITE);

while  (pin){ 
    pin=digitalRead(49);
    Time = millis();
  
   
                     // start read accelometer
  x_read = analogRead(0);
  Z_read =  analogRead(1);
  

          dataString ="T: ";
          dataString += Time;
          dataString +=" X: ";
          dataString += x_read;
          dataString +=" SX: ";
          dataString += Z_read;
      

if (dataFile) {
            dataFile.println(dataString);  }
          else {
            Serial.println("error opening datalog.txt");
          }   
  
   

delayMicroseconds(1000);


  }                   // While end
dataFile.flush(); 
dataFile.close();
pin=digitalRead(49);
delay(50);  
}

Thanks,
Yossi

I just seen this library to write to a USB disk on Key UsbFat

But this is also to write to a solid state device, do you think it will change anything?

Thanks,

You will always get a delay with a block oriented storage device. Most of your writes are stored in an internal 512 byte buffer. When the buffer is full, it is written to the SD.

SD cards have extra delays when flash needs to be erased or data needs to be moved for wear leveling.

USB flash will have similar problems.

It is possible to overcome the delay with extra buffering. See these examples, AnalogBin Logger, LowLatencyLogger.

For smaller amounts of data you can use SRAM or FRAM RamDisk.

Thanks you fat16lib, this should do the job. I will check this.

I see how you are helping all the guys here, you are doing a great job.

Thanks, Yossi