Try Embedded

Embedded file systems

FatFs, LittleFS and designing a reliable data logger.

When raw records are not enough

The previous lesson stored small records directly in flash. Once a product needs to keep many files of varying size, such as logs, recordings, configuration files or images, written by different parts of the code, a file system is easier and safer than inventing a format. Embedded file systems differ from desktop ones because they must survive power loss at any moment, run in a few kilobytes of RAM, and spread wear over flash.

The main choices

File systemMediaPower-loss safeWear levellingRAMNotes
FAT (FatFs)SD cards, USB sticks, eMMCNo (journal-less; a cut during a write can corrupt the table)No (relies on the card's controller)SmallReadable by every PC: use for removable media
LittleFSNOR flash, internal flashYes (copy-on-write, atomic updates)Yes (dynamic)Small, boundedThe usual choice for SPI NOR on MCUs
SPIFFSNOR flashPartlyYesGrows with file countOlder; no directories; largely replaced by LittleFS
FileX, Reliance Edge, TFFSVariousYes (transactional)SomeModerateCommercial or RTOS-bundled options
ext4, F2FS, UBIFS, squashfseMMC, raw NAND, read-only imagesext4 journals; UBIFS yesVia controller or UBILargeEmbedded Linux (see the userspace lesson)

A common product combination: LittleFS on an internal or SPI NOR chip for configuration and logs, plus FAT on an SD card for data the user takes to a PC.

How LittleFS stays consistent

LittleFS never overwrites data in place. Changes are written to new blocks (copy-on-write), and metadata blocks are updated by appending entries with checksums. A commit becomes visible only when its last entry is written; if power fails before that, the old version is still intact and is used on the next mount. There is no long "check disk" after a crash, and RAM use is bounded regardless of file system size.

Its trade-offs: random writes in the middle of large files are slow (copy-on-write rewrites blocks), and very full file systems spend more time on garbage collection. Keep some free space.

Using FatFs with an SD card

SD cards contain their own flash controller doing wear levelling and bad-block management, and present simple 512-byte sectors over SPI or the faster SDIO interface. FatFs provides the FAT layer on top:

FATFS fs;
FIL f;
UINT written;

if (f_mount(&fs, "", 1) != FR_OK) return ERR_NO_CARD;
if (f_open(&f, "log.csv", FA_OPEN_APPEND | FA_WRITE) == FR_OK) {
  f_write(&f, line, strlen(line), &written);
  f_sync(&f);                 /* flush data and directory entry to the card */
  f_close(&f);
}

Rules for reliability:

  • f_sync or close after important writes. Until then data and the file size live in RAM buffers; a power cut loses them.
  • Write in whole sectors or larger chunks. Small writes cause read-modify-write cycles inside the card, which are slow and wear it.
  • Handle card removal at any time, and check every return code.
  • Do not trust card timing: an SD card can stall for hundreds of milliseconds while its controller garbage-collects; buffer data in RAM (or a ring buffer in FRAM) so sampling is not blocked.
  • Prefer industrial-grade cards for products; consumer cards vary in endurance and power-loss behaviour.

Designing a logger

A data logger is a common interview design question. A solid design:

#include <stdio.h>
#include <string.h>

/* Records are batched in RAM and flushed in large aligned chunks, the pattern that keeps
   SD cards and flash fast and long-lived. Here the "card" just counts the writes. */
#define CHUNK 512
static char buffer[CHUNK];
static int used, card_writes, records;

static void card_write(const char *data, int len) { (void)data; (void)len; card_writes++; }

static void log_record(const char *line) {
  int len = (int)strlen(line);
  if (used + len > CHUNK) { card_write(buffer, used); used = 0; }   /* flush a full chunk */
  memcpy(buffer + used, line, (size_t)len);
  used += len;
  records++;
}

int main(void) {
  char line[48];
  for (int i = 0; i < 1000; i++) {
    snprintf(line, sizeof line, "%d,%d.%d,%d\n", 1700000000 + i, 20 + i % 5, i % 10, 40 + i % 7);
    log_record(line);
  }
  if (used) { card_write(buffer, used); used = 0; }
  printf("%d records written with %d card writes\n", records, card_writes);
  return 0;
}

Beyond batching:

  1. Sample in an interrupt or task into a RAM ring buffer, so storage stalls never lose samples.
  2. A lower-priority task formats and writes chunks, aligned to the sector or page size.
  3. Rotate files by size or date so one corrupted file loses little, and old files can be deleted to free space.
  4. Sync at a bounded interval (for example every few seconds) to cap data loss on power failure, and on a low-battery signal.
  5. Use a compact binary format with a header and CRC per block if space or speed matters; convert to CSV on the PC.

Choosing the storage format

NeedChoice
A few settings, rarely changedRaw records with CRC in internal flash (previous lesson)
Many settings or a few files, power-loss safeLittleFS on NOR flash
Large data the user copies to a PCFAT on an SD card or USB mass storage
High-rate counters or logsFRAM, with periodic transfer to flash
Embedded Linux systemext4 or F2FS on eMMC, UBIFS on raw NAND, squashfs for read-only images

Pitfall: Exposing the device's internal flash to a PC as a USB drive (FAT over MSC) while the firmware also writes to it corrupts the file system: two independent writers cache the same structures. Either the PC or the firmware owns the volume at any time.

Interview question: What happens if power fails while FatFs is writing a file, and how do you reduce the damage?

Answer: Data and the file's size and cluster chain may still be in RAM buffers or partly written, so the file can be truncated, contain unwritten clusters, or in the worst case the allocation table can be inconsistent, leaking space or cross-linking files. Reduce the risk by calling f_sync at bounded intervals and after important records, writing in large aligned chunks, rotating files so a damaged one loses little, detecting low supply voltage early to stop writing, and using power-fail hold-up capacitance where possible. For critical data, use a power-loss-safe file system instead.

Build it: find the flight log on the SD card

This is step 2 of the module project. The recorder also writes a long log to an SD card with a FAT file system, so a laptop can read it. A file on FAT is a chain of clusters scattered over the card, and to read or append to the log the firmware has to follow that chain itself.

Lab: Follow a FAT cluster chain to the right sector

The card uses FAT16. The file allocation table (FAT) has one 16-bit entry per cluster, and the entry for a cluster says what comes next:

EntryMeaning
0x0000the cluster is free: a file's chain must never lead here
0x0002 to fat_len - 1the next cluster of the file
0xFFF7a bad cluster
0xFFF8 to 0xFFFFend of the file

A directory entry gives the file's first cluster and its size in bytes. Clusters are 4 sectors of 512 bytes (2048 bytes), and cluster 2 starts at sector 100: cluster c starts at sector 100 + (c - 2) * 4.

  • fat_chain(fat, fat_len, first, out, max) follows the chain from first, stores each cluster in out and returns how many there are. It returns -1 if the chain is corrupt: it starts or passes through a cluster below 2, at or past fat_len, free or bad, or it has more than max clusters (which is how a loop shows up). A card that came out of a crashed drone is exactly when this happens, and the firmware must not hang.
  • sector_of(fat, fat_len, first, size, offset) returns the sector holding byte offset of the file, or -1 if offset is not inside the file (at or past size) or the chain is corrupt.

Going deeper

Interview question: How would you log a drone's flight data so a sudden power cut never corrupts it?

Answer: Use a power-fail-safe file system (littlefs, or FAT with care) or a simple append-only log with a header and CRC per record, sync at known points, and preallocate the log file. On boot, recover to the last valid record. If the logger has a little hold-up energy (a capacitor), detect falling voltage and flush in the time it gives.

Interview question: Why do SD cards sometimes stall for hundreds of milliseconds on a write?

Answer: The card's internal controller manages NAND flash: it maps logical sectors to physical pages, erases blocks and performs garbage collection and wear levelling. When it runs out of pre-erased blocks it must consolidate data before accepting the write, which can take a long time, and the SD specification allows write busy times of up to hundreds of milliseconds. Firmware must buffer incoming data so sampling continues during those stalls.

Interview question: Why write to flash or SD cards in large, aligned chunks?

Answer: The underlying flash programs whole pages and erases whole blocks. Small or misaligned writes force read-modify-write cycles: reading a page or sector, merging the change and writing it back, which is slower, consumes more energy and causes more wear (write amplification). Aligning writes to the sector or page size and batching them lets the storage program each unit once.

Explain it: In your own words, explain how a copy-on-write file system like LittleFS survives a power cut in the middle of an update.

Answer: It never modifies the existing data in place. A change is written into fresh blocks, and the metadata that points to the current version is updated by appending a new entry with a checksum. Only when that final metadata entry is completely written does the new version become the one the file system uses. If power fails earlier, the new blocks and partial entry are simply not referenced, or fail their checksum, so the next mount finds the previous complete version intact, with no repair step needed.