Enable SDCard
The SDCard driver and FAT file system library can be enabled in the iDev project properties under the feature settings:
Properties -> Indel iDev -> Feature settings -> Library -> Enable SDCARD and FAT file system driver
FAT file system Usage
The functions are modelled after the standard's open/close/read/write/gets etc functions. However they all start with a 'f_' prefix to not get confusion with the internal system functions. Please see the FatFS documentation for a deeper explanation of the functions.
The documentation of the FAT library and its functions is available under
FatFS
To use the FAT library include its header. It's not necessary to use the ifdef around it. However like that it's easier to disable the code if the application is also used on a target without an SDCard.
#ifdef INOS_FATFS
#include <ff.h>
#endif
Example: Scan card content
This example walks through all directories and prints the found items.
#ifdef INOS_FATFS
FILINFO Finfo;
DWORD AccSize;
WORD AccFiles, AccDirs;
FRESULT scan_files (
char* path
)
{
DIR dirs;
FRESULT fr;
int i;
fr = f_opendir(&dirs, path);
if (fr == FR_OK) {
while (((fr = f_readdir(&dirs, &Finfo)) == FR_OK) && Finfo.fname[0]) {
if (Finfo.fattrib & AM_DIR) {
AccDirs++;
i = strlen(path);
path[i] = '/'; strcpy(path+i+1, Finfo.fname);
fr = scan_files(path);
path[i] = 0;
if (fr != FR_OK) break;
} else {
printf("%s/%s\n", path, Finfo.fname);
AccFiles++;
AccSize += Finfo.fsize;
}
}
}
return fr;
}
void FatFSEx1()
{
FATFS FatFs;
FIL Fil;
UINT bw;
f_mount(&FatFs, "", 0);
AccSize = 0;
AccFiles = 0;
AccDirs = 0;
char pathbuffer[260];
pathbuffer[0] = 0;
scan_files(pathbuffer);
}
#endif
Example: Read a text file
This example opens a file for reading and dumps the text lines as eventlog traces.
#ifdef INOS_FATFS
void FatFSEx2()
{
FATFS FatFs;
f_mount(&FatFs, "", 0);
FIL Fil;
if (f_open(&Fil, "License.txt", FA_READ | FA_OPEN_EXISTING) == FR_OK) {
char buf[256];
while (f_gets(buf, sizeof(buf), &Fil)) {
printf(buf);
}
f_close(&Fil);
}
}
#endif
Example: Write a file
This example opens a file for writing and writes a string into it. The file can then be read on a normal computer with a card reader.
#ifdef INOS_FATFS
void FatFSEx3()
{
FATFS FatFs;
f_mount(&FatFs, "", 0);
FIL Fil;
if (f_open(&Fil, "newfile.txt", FA_WRITE | FA_CREATE_ALWAYS) == FR_OK) {
f_write(&Fil, "It works!\r\n", 11, &bw);
f_close(&Fil);
if (bw != 11) {
}
}
}
#endif
More examples are in the FatFS documentation. See the application note, "Extended Use of FatFs API".