yeuop
yeuop

Reputation: 169

How to deal with opening/closing files in Embedded C (STM32)?

I have a question about dealing with files in STM32. My project requires writing data to microSD card, but i don't know how to do this to have the best efficiency. My embedded program is like:

while(1)
{
fopen(filename,"a");

// write data to microSD card and send it via radio module

fclose(filename);
}

I am afraid that this code can be extremely slow, cause opening/closing file (especially external file on microSD card) in every loop of my program is expensive. How can I use fopen and fclose to keep code fast, but also to not loose data in program?

Upvotes: 0

Views: 836

Answers (1)

Clifford
Clifford

Reputation: 93514

The slowest part of this system is likely to be the SD card itself. Not only that; it will be variable - it will stream data consistently until it meets some physical or buffer boundary intrinsic to the specific card at which point it will stall for several milliseconds. Also the cards themselves vary widely, even for the same speed rating.

If you have real-time deadlines, writing to the SD card is ill-advised. Instead you might do better to use an RTOS and perform the SD card write in a lower priority task than the radio task, passing the data to the file task via a queue long enough to provide buffering to smooth out the file system latency.

Either way, if you are writing in small chunks, you would improve performance considerably by buffering data and writing in larger chunks that match the filesystem buffer size (typically 512 bytes). So rather than writing data as it arrives, you'd collate it in a buffer and write it when it reached the optimal chunk size. If using the RTOS method, you might have one task collating the data from the queue, then a third, even lower priority task with an input queue of at least two blocks to actually write the SD card.

Upvotes: 2

Related Questions