Power_Broker
Well-known member
I'm using the built-in SD interface on my T4.1 for datalogging and want to have as low of latency as absolutely possible. I'm using SdFat.h and have successfully tested the following sketch:
I realize this is likely not the most efficient way to write data to the SD card, but what is?
Thanks!
Code:
#include "SdFat.h"
#ifdef SDCARD_SS_PIN
const uint8_t SD_CS_PIN = SDCARD_SS_PIN;
#endif // SDCARD_SS_PIN
#define SPI_CLOCK SD_SCK_MHZ(50)
#define SD_CONFIG SdioConfig(FIFO_SDIO)
SdFs sd;
FsFile newFile;
double prevTime = 0;
double curTime = 0;
double diff = 0;
double period = 0;
double hz = 0;
long i = 0;
void setup()
{
Serial.begin(2000000);
while(!Serial);
if (!sd.begin(SD_CONFIG))
{
Serial.println("SD initialization failed\n");
while (1);
}
Serial.println("SD initialization succeeded\n");
newFile = sd.open("log.txt", FILE_WRITE);
Serial.println("Setup done");
}
void loop()
{
prevTime = micros();
newFile.println(i);
i++;
if (!(i % 100))
{
newFile.flush();
newFile.close();
newFile = sd.open("log.txt", FILE_WRITE);
}
curTime = micros();
diff = curTime - prevTime;
period = diff / 1000000.0;
hz = 1.0 / period;
Serial.print("diff: "); Serial.println(diff);
Serial.print("period: "); Serial.println(period);
Serial.print("hz: "); Serial.println(hz);
Serial.println();
}
I realize this is likely not the most efficient way to write data to the SD card, but what is?
- Should I batch the data inside a buffer and write the entire buffer at once?
- What should the buffer size be?
- Also, can I set the `SPI_CLOCK` value over 50MHz?
- When periodically saving the data, should I use both `flush()` and `close()` or just `close()`? (I'm streaming data and the sketch won't be able to tell when power will be cut or the card removed)
Thanks!