Writing SD Card takes extra time after every 0.2 seconds

Hi,

I am trying to write floating point number on SD card and it takes 500 usec on average but after every 0.2sec it takes around 9500 usec. I am using micros(); function before and after the writing command to calculate the time it takes as shown below:

previousMillis=micros();

* MPUData.println(acc);*

* Serial.println(micros() - previousMillis);*

where acc is floating point number and MPUData is my File.

I am using MPUData.flush(); after every 100 samples.

Can you guys suggest me why this writing time is showing discrepancy?

I am using Arduino 1.8.4.

The attached file shows the discrepancy in writing time.

Thanks.

Buffering?

I'd post a more detailed explanation, but I can't see your code.

Yes.

Got huge code but attaching trimmed version that includes all SD Card commands.

sketch_oct18SDCARD.ino (1.2 KB)

I'm posting from my phone; I still can't see your code.

Good luck.

previousMillis=micros();

Now, doesn't that look stupid.

There is NOTHING magic about the name you store time in. Don't use Millis in the name if you don't want to look stupid when you need finer-grained control.

AWOL:
I'm posting from my phone; I still can't see your code.

Good luck.

#include <SD.h>

#include <SPI.h>

#include "I2Cdev.h"

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif

File MPUData;
int j=1;
unsigned long previousMicros = 0;
float acc = 0;

void setup() {

Wire.speed = 400;
Serial.begin(115200);
//-------------------------------------------------------------
// Open serial communications
SPI.begin();
Serial.print("Initializing SD card...");
// pinMode(SS, OUTPUT);
// see if the card is present and can be initialized:
if (!SD.begin(SS))
{
Serial.println("Card failed, or not present");
// don't do anything more:
return;
}
Serial.println("card initialized.");

// Open up the file we're going to log to!
MPUData = SD.open("data.txt", O_CREAT | O_APPEND | O_WRITE);
if (! MPUData) {
Serial.println("error opening datalog.txt");
// Wait forever since we cant write data
while (1) ;
}
//-------------------------------------------------------------

}
void loop() {

// getacc();

previousMicros=micros();

MPUData.println(acc);

Serial.println(micros() - previousMicros);

if((j%100)==0)
MPUData.flush();
j++;

}

Can you guys suggest me why this writing time is showing discrepancy?

Most of the time, when you "write to a file" you are actually writing to a buffer. That is fast.

When the buffer gets full, though, the contents of the buffer have to be committed to the card. That is NOT (as) fast.