Tag: file allocation table

In the last week’s part 1 of my FAT and SD tutorial, we got as far as reading the file entries in root directory, and peeking into a file with hex editor. Now we’ll cover the file allocation table itself to enable reading longer files, and adapt the code into a small footprint FAT16 library!

File allocation table in FAT16

In the previous part, we learned that the data on a FAT-formatted disk is stored in clusters. In our test image, the cluster size was 32 sectors, i.e. 16 kiB (16 384 bytes). Let’s imagine a newly formatted disk with 100 free clusters, with the clusters numbered from 2 (the first cluster at the beginning of data area) to 101 (the very last cluster). Now let’s copy some files there:

File operation

File allocation

Copy HAMLET.TXT (193 082 bytes) to disk

Clusters 2-13 allocated for the file (196 608 bytes)

Copy README.TXT (353 bytes) to disk

Cluster 14 allocated for the file

Create SUBDIR on disk

Cluster 15 allocated for the directory file entries

Create 1.TXT in SUBDIR

Cluster 16 allocated for the file, a new file entry written to SUBDIR (beginning of cluster 15)

Are you limited by 128 bytes of EEPROM on your MCU or even the few kilobytes of flash in your project? Instead of just downloading a library like Petit FAT File System Module and following blindly a tutorial on how to customize it to your microcontroller and SD card, would you like to really understand what you are doing, and maybe learn a bit about filesystems and SPI in the process?

In this first part of my FAT and SD tutorial, we’ll take a SD card image, and create a simple C program to interpret its contents. For this part, you don’t need any hardware at all, just a computer with gcc (GNU C Compiler) or any other ANSI C compatible compiler installed.

Getting ready: Hex editor and disk image

To make the coding easier, I recommend a good hex editor. The one I’m using is the free and excellent HxD by Maël Hörz. You can also use it to create a 1:1 disk image from a physical SD card. To have a filesystem to read, I purchased a 1 GB micro-SD card with SD adapter for 5€, plugged it into my computer and formatted it as FAT16 (over 2 GB cards will likely get formatted as FAT32), and copied Hamlet from Project Gutenberg and some other dummy test files to it (also created a subdirectory with a few text files in it):