FatFs 是一個小型、獨立的 FAT 檔案系統模組,適用於嵌入式系統。本文記錄在 STM32 平台上移植 FatFs 0.09 版本的完整過程,包含底層介面實現、上層 API 使用範例與 SD 卡驅動整合。
移植時需實現 diskio.h 定義的五個介面函數:
| 函數 | 功能 |
|---|---|
disk_status | 取得裝置狀態 |
disk_initialize | 初始化裝置(如 SD 卡) |
disk_read | 讀取扇區資料 |
disk_write | 寫入扇區資料 |
disk_ioctl | 裝置控制命令(如取得扇區大小、磁碟大小) |
另需提供 get_fattime 回傳當前時間戳,供檔案建立/修改時間使用。
// 初始化
DSTATUS disk_initialize(BYTE drv) {
if (SD_Init() != SD_OK) return STA_NOINIT;
return RES_OK;
}
// 讀取扇區
DRESULT disk_read(BYTE drv, BYTE *buff, DWORD sector, BYTE count) {
if (count > 1) {
SD_ReadMultiBlocks(buff, sector * BLOCK_SIZE, BLOCK_SIZE, count);
SD_WaitReadOperation();
while (SD_GetStatus() != SD_TRANSFER_OK);
} else {
SD_ReadBlock(buff, sector * BLOCK_SIZE, BLOCK_SIZE);
SD_WaitReadOperation();
while (SD_GetStatus() != SD_TRANSFER_OK);
}
return RES_OK;
}
// 寫入扇區
DRESULT disk_write(BYTE drv, const BYTE *buff, DWORD sector, BYTE count) {
if (count > 1) {
SD_WriteMultiBlocks((uint8_t*)buff, sector * BLOCK_SIZE, BLOCK_SIZE, count);
SD_WaitWriteOperation();
while (SD_GetStatus() != SD_TRANSFER_OK);
} else {
SD_WriteBlock((uint8_t*)buff, sector * BLOCK_SIZE, BLOCK_SIZE);
SD_WaitWriteOperation();
while (SD_GetStatus() != SD_TRANSFER_OK);
}
return RES_OK;
}
f_mount(0, &fs); (邏輯磁碟號 0~9,對應 _VOLUMES)// 新建檔案寫入
res = f_open(&fnew, "0:newfile.txt", FA_CREATE_ALWAYS | FA_WRITE);
if (res == FR_OK) {
f_write(&fnew, textFileBuffer, sizeof(textFileBuffer), &bw);
f_close(&fnew);
}
// 開啟現有檔案讀取
res = f_open(&fnew, "0:newfile.txt", FA_OPEN_EXISTING | FA_READ);
if (res == FR_OK) {
f_read(&fnew, buffer, sizeof(buffer), &br);
f_close(&fnew);
}
f_mount(0, NULL);FA_READ:讀取存取FA_WRITE:寫入存取FA_OPEN_EXISTING:開啟現有檔案,不存在則失敗FA_OPEN_ALWAYS:開啟或建立新檔FA_CREATE_NEW:建立新檔,已存在則失敗FA_CREATE_ALWAYS:建立新檔,已存在則截斷覆寫
char fname[40];
short idx = 0;
FIL fp;
do {
sprintf(fname, "0:ScreenShort/SS_%d.bmp", idx++);
if (idx > 500) return;
res = f_open(&fp, fname, FA_CREATE_NEW | FA_WRITE);
} while (res != FR_OK);
// 寫入資料...
f_close(&fp);

應用層呼叫 FatFs API → FatFs 核心模組 → 底層 diskio 介面 → SD 卡驅動 → 硬體控制器。
_FS_READONLY = 0 以支援寫入操作_VOLUMES 設定足夠的邏輯磁碟數FATFS 與檔案物件 FIL 需靜態分配或動態管理生命週期