stm32f103单片机用fatfs读写sd卡测试代码
时间: 2023-10-26 08:05:40 浏览: 208
读写FAT32文件系统的SD卡实验
您好,我能够为您提供以下的代码作为参考:
```
#include <stdio.h>
#include "ff.h"
#include "diskio.h"
#define BUFFER_SIZE 512
FATFS fs;
FIL fil;
FRESULT fr;
BYTE buffer[BUFFER_SIZE];
int main(void) {
// Mount SD card
fr = f_mount(&fs, "", 0);
if (fr != FR_OK) {
printf("Could not mount SD card!\n");
return 1;
}
// Open file for writing
fr = f_open(&fil, "example.txt", FA_WRITE | FA_CREATE_ALWAYS);
if (fr != FR_OK) {
printf("Could not open file!\n");
return 1;
}
// Write data to file
UINT bytes_written;
fr = f_write(&fil, buffer, BUFFER_SIZE, &bytes_written);
if (fr != FR_OK) {
printf("Could not write to file!\n");
return 1;
}
// Close file
fr = f_close(&fil);
if (fr != FR_OK) {
printf("Could not close file!\n");
return 1;
}
// Open file for reading
fr = f_open(&fil, "example.txt", FA_READ);
if (fr != FR_OK) {
printf("Could not open file!\n");
return 1;
}
// Read data from file
UINT bytes_read;
fr = f_read(&fil, buffer, BUFFER_SIZE, &bytes_read);
if (fr != FR_OK) {
printf("Could not read from file!\n");
return 1;
}
// Close file
fr = f_close(&fil);
if (fr != FR_OK) {
printf("Could not close file!\n");
return 1;
}
// Unmount SD card
fr = f_mount(NULL, "", 0);
if (fr != FR_OK) {
printf("Could not unmount SD card!\n");
return 1;
}
return 0;
}
```
这是一个简单的测试代码,可以用于读写SD卡。可根据实际情况进行代码修改。
阅读全文