Library 21- Read SD card with FatFs on STM32F4

Finally I got it working properly. Reading SDcard was very awesome for me for first time, so I decided to make a library for STM32F4xx devices and post it to my website. It’s basically just communication interface between STM32F4 and FatFS library by Chan. It supports SPI or SDIO communication. Library also supports USB communication, but for that purpose you need USB stack too. USB is available here.

Below I’m showing how to setup everything with STM32F4 to get SD card working with SPI or SDIO communication.

FATFS library can be used everywhere, but really, everywhere, not just SDCARD or USB flash drive. I’ve made an update to use source for FATFS SDRAM on STM32F429-Discovery or STM32F4x9-EVAL boards. Click here for more info.

Future updates will include also SPI FLASH (prototoype functions are added to FATFS library but not implemented yet) and option for user to add custom functions for FATFS low level.

FatFS Library

If you are interested for FATFS using HAL drivers, check here.


  • Fatfs by Chan supported, version R0.11
  • Support for SDIO or SPI interface
    • SDIO works with 1- or 4-bit mode
  • Support for Card detect pin
    • Can be disabled
  • Support for Write protect pin
    • Can be disabled
  • Custom fat time
    • Enables you to implement your own time using RTC
  • Updates
    • Version 1.2 – August 29, 2014
    • Version 1.3 – December 06, 2014
      • FatFs version R0.10C now implemented
    • Version 1.4 – December 29, 2014
      • Added support for truncate file from beginning
    • Version 1.5 – February 17, 2015
      • FatFs version R0.11 now implemented
      • Fixed problem which appers sometime using SDIO


    • STM32F4xx
    • STM32F4xx RCC
    • STM32F4xx GPIO
    • STM32F4xx SPI (only when SPI)
    • STM32F4xx DMA (only when SDIO)
    • STM32F4xx SDIO (only when SDIO)
    • MISC (only when SDIO)
  • TM
    • TM SPI (only when SPI)
    • TM DELAY (only when SPI)
    • TM GPIO
    • defines.h
    • attributes.h
  • FatFs by Chan (included in library)


SDCard pinout

SDCard pinout

Because different connections are possible, you have different pinouts. They are in table below:

NR SDIO Interface SPI Interface
Name STM32F4xx Description Name STM32F4xx Description
4-bit 1-bit
1 CD/DAT3 PC11 Connector data line 3 CS PB5 Chip select for SPI
2 CMD PD2 PD2 Command/Response line MOSI PA7 Data input for SPI
4 VDD 3.3V 3.3V 3.3V Power supply VDD 3.3V 3.3V Power supply
5 CLK PC12 PC12 Clock SCK PA5 Clock for SPI
7 DAT0 PC8 PC8 Connector data line 0 MISO PA6 Data output for SPI
8 DAT1 PC9 Connector data line 1
9 DAT2 PC10 Connector data line 2

Card detect and write protect pins are not part of SD card, but part of SDcard connector. They are listed below, and are same for both communications:

Name STM32F4xx Description
WP PB7 Write protect pin. Pin low when write is enabled
CD PB6 Card detect pin. Pin low when card detected

By default, both pins are disabled in library. If you want to use them, you have to enable them in defines.h file

SDIO Communication

STM32F4xx has internal SDIO peripheral to work with SD cards. Also, SDIO communication is faster than SPI, but if you don’t need speed in your project, you can use SPI aswell. With default settings, SDIO 4-bit mode communication is used. It means, that you need all four data lines. SDIO also supports 1-bit mode, where you need only Data0, CMD and CLK pins. To activate 1-bit mode, add this to your defines.h file:

To be able to get SDIO to work, you have to include these files:

  • tm_stm32f4_fatfs.h
  • tm_stm32f4_fatfs.c
  • fatfs/diskio.h
  • fatfs/diskio.c
  • fatfs/ff.h
  • fatfs/ff.c
  • fatfs/ffconf.h
  • fatfs/integer.h
  • fatfs/option/syscall.c
  • fatfs/option/unicode.c
  • fatfs/drivers/fatfs_sd_sdio.h
  • fatfs/drivers/fatfs_sd_sdio.c

And also make sure, that you include all STM32F4xx peripherals to work with. What it needs is described under “Dependencies” section.

SPI Communication

If you want to use SPI communication instead of SDIO on STM32F4xx for any reason, you can do that. To enable SPI communication, open your defines.h file and set constant

Now, SPI is activated. Make sure, that you include dependencies libraries, described in “Dependencies” section. By default SPI1 is used with Pinspack 1, but you can set it to your own SPI (in defines.h file) with

Look here to see, which pins are associated with each SPI. For SPI is also used CS (Chip select) pin. You can leave it’s settings as it is, or change it to what you want. You can do this with (in defines.h)

To properly work with SPI communication, you need files below:

  • tm_stm32f4_fatfs.h
  • tm_stm32f4_fatfs.c
  • fatfs/diskio.h
  • fatfs/diskio.c
  • fatfs/ff.h
  • fatfs/ff.c
  • fatfs/ffconf.h
  • fatfs/integer.h
  • fatfs/option/syscall.c
  • fatfs/option/unicode.c
  • fatfs/drivers/fatfs_sd.h
  • fatfs/drivers/fatfs_sd.c


To work with files, you have to use fatfs library. In order to get it work properly, you should check it’s manual here. My library is used only for “behind the scenes” settings, to get communication with SD card properly.

Custom get_fattime() function

Fatfs supports get_fattime() function, which returns time in integer format. By default get_fattime() returns time 0. That means 1.1.1980 00:00:00 time. If you have any RTC library or you want to set your own time, then you should set define in defines.h file:

After you set this, you have to create your project function:

My libraries for RTC


  • Fixed error for SPI communication

My functions

I have also made some additional functions:

  • TM_FATFS_DriveSize
    • Get full drive size and free space on your disk
  • TM_FATFS_TruncateBeginning
    • Truncate file from beginning

What could possibly go wrong?

You know, Murphy’s law 🙂 In this section I will add possible problems and (I hope) how to get it fixed.

  • Card not recognized by Fatfs
    • Is your card formatted in FAT16 or FAT32 format?


I have test this example with SPI and SDIO interface. In both cases I got the same result. I used 2 and 8GB cards in FAT16 format. In example below, default settings are in use, so:

  • SDIO interface
  • Card detect OFF
  • Write protect OFF
  • Led status
    • No leds on: It has not been mounted ok
      • Check if pinout is correct, also make sure FAT16 is selected
    • Only GREEN led on: mounted ok and opened ok, but data could not be written
    • Only RED led on: mounted OK, but could not open file
      • Maybe you have enabled Write protect pin. Disable it for this example
    • Both ON: everything OK

Example result with FatFS on STM32F429 Discovery

Example result with FatFS

View project on Github, download library below.

TM STM32F4 FATFS Library

Read SD card with SDIO or SPI on STM32F4xx using FatFS by Chan


Owner of this site. Also electronic enthusiasts, web developer, 3D printer fan, handball player and more. Big fan of STM32F4 devices. In anticipation of the new Discovery board for STM32F7 lines.

You may also like...

Read before commenting!

Before you make a new comment, make sure you agree with things listed below:

  • - Read post to make sure if it is already posted what you are asking for,
  • - Make sure you have the latest version of libraries used in your project,
  • - Make a clean and grammatically correct written message,
  • - Report as many details as possible, including what have you done so far,
  • - Do NOT post any code here. Use Pastebin,
  • - Do NOT post any error codes here. Use Pastebin,
  • - Specify STM32Fxxx family and used Discovery/EVAL/Nucleo or custom made board,
  • - Make sure your clock is set correct for PLL,
  • - If you are using my HAL drivers, please check this post how to start.
Comment will be deleted on breaking these rules without notification!
  • Hi ,
    On your example i don’t see the SD_Init() , is it called from another ‘c’ file ?

    • Yes, because there is not SD_Init() function in main. Everything si performed “behind the scenes”, you just need to know how FATFS works.

  • Andrew

    Hi TM,

    I’ve tried to import your library for use on my STM32F407. I don’t get any compilation errors but I do get these 2 link errors:

    Error: L6200E: Symbol SysTick_Handler multiply defined (by hal_cm4.o and tm_stm32f4_delay.o).

    Error: L6200E: Symbol DMA2_Stream3_IRQHandler multiply defined (by dma_stm32f4xx.o and fatfs_sd_sdio.o).

    Systick_Handler only appears in the project 4 times, once when your ‘tm_stm32f4_delay.c’ calls it and the rest in ‘startup_stm32f40_41xxx.s’, where I do not spot anything strange but the workings of .s files are outside of my knowledge.

    DMA2_Stream3_IRQHandler appears 7 times in code and comments but I only see one instance of a #define. Even when I throw a #ifndef around this definition I get the same error. So I commented out the definition and I STILL get the same error..

    I’ve been through your checklist and I’m quite sure that I have included all necessary files. Do you have any ideas on these errors?

    Thanks very much.

    • It looks like you are using HAL drivers, which are not supported for this library.

      This library supports only basic CMSIS drivers.

      • Andrew

        Thank you for your help.

        I have adjusted the drivers and now I have the program compiled and running your example test on my board. My SD card appears to mount successfully, but it is FAT32 so the program fails at the f_open attempt.

        I can’t find a program for Windows 8 that will allow me to format in FAT16 and I would prefer to use FAT32 anyway, so I am looking through your example main() file to find where you set the default as FAT16, so that I can change it to FAT32 to match my SD card.

        From reading the code I believe I should be looking for something like:

        FATFS.fs_type = FS_FAT16;

        But I can’t find the point in the code where the FS_FATxx #defines are actually used to define anything. I’m sure it must be set somewhere as it looks like the fs_type should default to FAT12 based on this:

        /* Determine the FAT sub type */
        sysect = nrsv + fasize + fs->n_rootdir / (SS(fs) / SZ_DIR); /* RSV+FAT+DIR */
        if (tsect csize; /* Number of clusters */
        if (!nclst) return FR_NO_FILESYSTEM; /* (Invalid volume size) */
        fmt = FS_FAT12;
        if (nclst >= MIN_FAT16) fmt = FS_FAT16;
        if (nclst >= MIN_FAT32) fmt = FS_FAT32;

        Can you please point me to where I can find this default fs_type so that I can change it to FAT32?

        Thanks very much.

        • If you successfully mount your card, then can be problem with write protection, or too long file name. Try filename lets say test.txt if it works.

    • Andrew

      Silly me…the second case was in fact multiply defined. Once in fatfs_sd_sdio.c and once in DMA_STM32F4xx.c. I removed the former definition for now.

      Systick_Handler is still puzzling me. Hopefully you can shed some light on this. Thanks.

      • DMA_STM32F4xx.c is not name for standard peripheral library.

        Try to add KEIL_IDE to your project defines, under “Options for target” -> C/C++ -> Defines

  • sarath tv

    Hi Tilen,
    the example you have given here will work for SPI interface also,Right? provided we make the necessary changes in define.h file.?

    • Did u check article content?

      • sarath tv

        hi Tilen,

        am getting a error

        diskio.c(211): error: #167: argument of type “void *” is incompatible with parameter of type “BYTE”
        the line corresponds to :
        status = TM_FATFS_SD_disk_ioctl(buff, buff);

        in the defintion of the function arguments are BYTE and void *pointer.

        and also at

        disco.h(165): error: #35: #error directive: “Please select your board”.

        do you know why this is happening.?

        • I don’t know which compiler you are using, but with ARM or GCC compiler works just great.
          error in disco.h is because you didn’t select which board you are using.
          Open disco.h file and look which defines you have to set to enable your board. If you are working with custom application, then this library is pointless for you.

          • sarath tv

            i am using KEIL uvision 4 IDE. i have enable the stm32f429zi board .but still showing error like undefined symbol SystemInit .

          • You need CMSIS files for STM32F4. Keil uVision 4 does not have it by default. Install uVision 5 🙂

          • sarath tv

            ohh…thanks for the help?.

          • sarath tv

            even with keil 5 i am encountering errors ..
            Objectsspi.axf: Error: L6200E: Symbol SysTick_Handler multiply defined (by hal_cm4.o and tm_stm32f4_delay.o).
            this errror should go if i remove one of the c files . right ? but where is the hal_cm4 file.
            please help?.

          • Disable hal drivers!

          • sarath tv

            how to do that ? i have added only CMSIS component .nothing else.? if i am correct the hal driver gets added only if i add cmsis drivers..isnt ..? sorry if i am wrong

          • No. Cmsis are cmsis and hal are hal. This is not the same and is not compatible.

          • sarath tv

            i have not selected any hal?. y is this error comming then

          • I suggest you that you create new project and copy main.c and other files inside. You have explained on my site how to make it.

          • sarath tv

            is this program valid only for FAT16 sd card ?

          • It supports everything what FatFS library supports.

          • sarath tv

            hey thanks for the help. but the response program is showing inconsistent behavior in terms of card initialization. the program was running successfully for 3-4 times then it stopped working. i cross checked the hardware and there seems to be no problem there. have you ever come across this kind of problems?

  • sarath tv

    What is the maximum throughput you got with this program?

    • No idea what you wanna hear.

      • sarath tv

        PS Old theme was better This looks ancient .. 😉

  • Linard J.

    How can I read a string from a text file on the SD Card ?

    And does the program create the file “1stfile.txt” or do I have to copy it to the SD Card ?

    • Use f_gets for this.
      File will be created by code.

      • Linard J.

        Thank you
        I want to read Touchscreen data, save it to the SD Card and then read it out from the SD Card. I think the best idea is to make two Arrays x() y(). How could I save a Array to the SD Card and then read it out again ?

  • Dracog71

    Hi TM! , First of all, i’m very thankfull of your help.

    I’m trying to compile this “read SD card” in CooCox IDE, but when i build the proyect it gives me a tons of errors in “fatfs_sd_sdio.c” , every single line! , errors like this :

    [cc] C:UsersDracog71DocumentsEDESIGNARMPruebas Shield discoveryfatfsdriversfatfs_sd_sdio.c:244:1: error: unknown type name ‘SDIO_InitTypeDef’
    [cc] SDIO_InitTypeDef SDIO_InitStructure;
    [cc] ^

    plz gimme a light! …

    • I would say that you miss SDIO module for stm32f4. Enable it in coocox like you emable rcc, gpio, etc.

  • sarath tv

    hi TM , need your expertise . the code was working fine then one day it started behaving odd. The program stopped working. It mostly returns from card not initialized response. I checked the hardware (SD card ) in msp430 and it was working fine, and i cross checked the connections and i am sure there is nothing wrong in the code also. so y is it behaving like this?. any ideas .

  • zoli emqua

    HELP ME : ..FATFSdiskio.c(47): error: #5: cannot open source input file “fatfs_sd_sdio.h”: No such file or directory

    • if you are using keil uvision, then in target settings set include paths where this file is.

      • zoli emqua

        ..FATFSdiskio.c(211): error: #167: argument of type “void *” is incompatible with parameter of type “BYTE”

        can you help me?

      • zoli emqua

        you can send me a sample project ?
        thank you very much !!

  • محــمد مهــدی سلطانی

    have you ever writen a file like a jpeg to sd card?

    • and also read .mp3 files

      • محــمد مهــدی سلطانی

        and do you have any source to learn from it?
        or we should just change the name of the folder to .jpg or .mp3 or something else?

        • you can read/write any type of file you want.
          The question is if you can interpret data from file properly.

          You can use .mp3, .jpg,.whatever for your logging where the sun is every 5 seconds.

  • Elis Purkov

    I need a help. When i try to read a wav file, function f_read() always reads zero bytes. In the FIL struct there is also fsize field which indicates size of zero bytes although real size is around 2 MB. besides that, there is a value 0x01 in a flag field and other values in id, dir_ptr and dir_sect fields. What do you think is the problem?

    • Hi.

      Are you trying to read 2MB with a single read? That’s quite big.
      Next, is your file opened for read mode?

      • Elis Purkov

        Hi. I’ve tried to read two bytes at a time. It was probably something wrong with a file. I’ve tried to delete a file and copy it again on sd card. Now it reads ok.

        • Huuh, nice to hear that 🙂
          Have a nice coding 🙂

          • zoli emqua

            hi .
            FATFSdiskio.c(211): error: #167: argument of type “void *” is incompatible with parameter of type “BYTE”

  • zoli emqua

    .FATFSdiskio.c(211): error: #167: argument of type “void *” is incompatible with parameter of type “BYTE” .

    can you help me fix this ?

    • You can download library again. Error has been fixed right now.

  • zoli emqua


    Can you help me read /write mmc card?

    i have tried to do with mmc but fail.

  • Dracog71

    I need your expertise! … you told that with this library i can read MP3 files… with f_get() …

    How can i reproduce it ?? … i’m really noob in this, so, i need another library to reproduce it? , can you plz upload come codde to understand how it works? …

    I’ts gonna be really amazing if i can reproduce some music in the STM32f4 discovery !! …

  • Marcin

    I have made the necessery changes in defines.h, to set the 1-bit SDIO mode

    #define FATFS_SDIO_4BIT 0

    i have connect all 3 pins PC8 – dat0, PC12 – clk and PD2 – cmd to my sd card.

    While executing the example code, the card does not initialize. I debugged it and i dont get any response from the card (SD_ILLEGAL_CMD) while sending the first CMD55 in SD_PowerOn() function.

    I have no idea, what could be wrong, but i’m sure i messed something up, because everybody seem not to have theese problems. I use CooCox, stm32f407vg.

    The only thing, that is not ok is that, there is an error while debugging

    Reading symbols from D:DropboxuCSTM32Praca IngSDIOSDIODebugbinSDIO.elf…done.
    file “D:/Dropbox/uC/STM32/Praca Ing/SDIO/SDIO/Debug/bin/SDIO.elf”
    file “D:/Dropbox/uC/STM32/Praca Ing/SDIO/SDIO/Debug/bin/SDIO.elf”
    set tdesc filename C:/CooCox/CoIDE/bin/target_desc/arm-with-m.xml
    target remote
    Default_Reset_Handler () at D:DropboxuCSTM32Praca IngSDIOcmsis_bootstartupstartup_stm32f4xx.c:267
    267 {
    tbreak main
    Temporary breakpoint 7 at 0x80007b0: file D:DropboxuCSTM32Praca IngSDIOmain.c, line 18.

    Any ideas?

    • Huh, error while debugging?
      Please confirm that you put GND on both gnd pins on card.

      • Marcin

        I use the Atnega32 evaluation board for sd card docking, so the connections are all ok. The error is not realy an error i guess, just an information posted in red colour. I get it also in other working versions of my projects. I use 2 GB sd card in FAT so i guess here there is no problem here. I have 168 MHz clock , so initialuzation of the card is under 400 kHz. i used this card in a fatfs spi communication and it worked, so i think made some mistake implementing your library. I just need fresh look in it, some ideas i havent yet considerate. Thanks for quick reply.

        • I have to make a research about that.
          Can’t help you right now, because I don’t have discovery board here.

          • Marcin

            Maybe i have some clock issue… Shuld i clock my uC at 168MHz or 180MHz? And why do i need delay, if i use SDIO communication?

          • Try with 168.

          • Marcin

            I used both… what abuty this uVision project, any ideas?

          • Give me some time, that I come home and test. For which board you use?

          • Marcin

            Discovery STM32F4(07VGT6 )

          • Oh, right. I was testing this. Without problems.
            Also, I tried with F429 Discovery, no problems.

            It looks like there is problem on your side somewhere.

          • Marcin

            I have following connections on the ATMEGA Board:

            Maybe here is the problem?

            After sending command CMD 55 in SD_PowerOn() i get errorstatus SD_ILLEGAL_CMD), because he reads only zeroes as the responding command.

          • Marcin

            I downloaded now the whole project from your github and built it with uVision 5. After download in debug mode, the program goes into HardFault_Handler while doing GPIO_Initialisation for SDIO use. In the function SD_LowLevel_DeInit. If i go step by step through this function (using F11), then it doesnt go into HardFault_Handler. I have no ideas what might be wrong, cause i use your project…

  • Alirio Filho

    I have tried use your code with me stm32f417 but at line TM_Delay_init() this stop and keep in this line. I’m new on STM. You can realize why code dont continue running passing at this line? I’m using SPI 1bit.

    • Hi.
      I would say that you have not properly set clock for your STM.
      And then systick cannot be set properly and while(1) loop is executed.

      If you send me your project I can check your settings.

      • Alirio Filho

        i’ll send to you me project.

        Now after see a tutoria in this site about clock config,the code pass from TM_Delay_Init() and stop at Delay(); function ><

        • You definitelly have problem with your clock and interrupt handler settings. You can send me on privete email your project.

          • Alirio Filho

            ok, alread send the e-mail. Just forget say my bord is this:


            So STM32F417ZGT6.

          • Alirio Filho

            Thanks a lot Tilen, this work now, see after u adjust stm32f4xx_it file. I back external oscilator to 25.
            Only one question. I test tree card. 512mb, 1Gb and 2Gb, only mount 2Gb. read a bit on site from Fatfs and no see any limitation. on PC cards reads, u know anything about this?
            my projets is simply, not need bigs sdcards.

            ah, formatted cards in fat, fat16 and 32, change block size but notinhg harpness

          • Iz might happen that some cards will never be recognized by fatfs, no matter on which format they are.
            I can’t help you here. You should post this message on fatfs user forum.

  • vukasheen

    I have used library to write binary data into the file with my discovery board.

    I have an issue when I am trying to write sequence “0xAEAE” into a file using f_write function. Instead “0xAEAE” bytes I get the file with next byte sequence “0xD0BED0BE” .

    Do you have an idea why?

    Can anyone try to confirm this bug?

    • There might be a bug, I don’t know if it is FatFs or my communication.
      Can you try to test both communications?
      So SPI and SDIO.

      Also, how many data you tried to write in one packet?

      • vukasheen

        Hi Majerle,

        The situation is the same even if I write this two bytes or buffer of 1000 bytes. When sequence “0xAEAE” or “0xEEEE” is written, FatFS writes four bytes sequence: “0xBED0BED0”.

        So if I write 1000 bytes with one sequence of “0xAEAE” I will get 1002 bytes in file.

        Currently I work with this example SDIO + DMA. I can test SPI connection until the end of week.

        • That would be great if you can test SPI aswell.
          That would probably tell us where is problem.

          • vukasheen

            Hi Majerle,

            I have tested SPI mode. Unfortunately the problem still persist.

            What we can do next?

          • Hi,
            you should report problem to FatFs forum about that.
            This is not bug in my lib.

  • Miguel Moreto

    Hello Majerle,

    again, thank you so much for these libs! they are great and very well coded! Congratulations!

    I would like to inform you that this lib is working very well with my ST NucleoF401 board.

    I use Cocoox CoIDE with ARM GCC. Because of this I had to modify the definition of the __weak atribute to functions (used in get_fattime funcition).

    I just added to my defines.h:

    #define __weak __attribute__ ((weak))

    As I’m using SDIO interface and I didn’t want to load the unnecessary libs, delay, usart and spi, I commented the folowing lines in fatfs_sd_sdio.h

    //#include “tm_stm32f4_spi.h”
    //#include “tm_stm32f4_usart.h”
    //#include “tm_stm32f4_delay.h”

    Your lib is very good! I tried hard with the STM32 CubeMx lib to get SDIO working, but had no success. That Cube lib (and also CubeMX software) are buggy, your lib is much better! Thanks!

    Best regards,

    Florianopolis – Brazil

  • 溫方志

    Hello Majerle, I use spi mode to read sd card. Its success runs at stm32f429(both led on) but fail at Discovery STM32F4(07VGT6)(no led, fail at diskinit). I think my pin assessment is right. Can you help me? And thank you create this library let us use

    • Hi.
      Which spi/pins are in use? Also, whics cs pin you use for card?

      • 溫方志

        all use default and cs pin is use PB5

        • Then I don’t see any other options.
          If it worked on F429 then it should on F407 too. You have probably failed somewhere in pinout.

          Soory, I don’t see any other options here.

        • Marcin

          It seems we have the same problem, but i use SDIO 1 BIT. The cardx does not reply, sends neither commands nor data. Also using the f407vgt6

        • As I said yesterday, I’ve made new test today:

          STM32F4-Discovery default SPI: works
          STM32F429-Discovery default SDIO: works
          STM32F429-Discovery SDIO 1-bit: works

        • 溫方志

          It seem is select() fail. Timeout at select() function. i think i am close. Thanks for reply

        • 溫方志

          May i ask what hardware you use. I think it may be a hardware problem. I use welding gun to connect my sd card. May be I need an sd card module and thanks your help

          • Normal connector for SD card ith soldered pins on to connect to discovery.

    • 溫方志

      I only add
      #define FATFS_USE_SDIO 0
      this line at define.h
      success runs at stm32f429 but fail at 07VGT6

  • Dung VN

    Hello Majerle, I use your Fatfs library. when i remove F_FRESULT = f_open(&fil, “ABC.txt”,FA_OPEN_EXISTING| FA_READ); and build then load code to my kit, it run ok but when i don’t remove F_FRESULT = f_open(&fil, “ABC.txt”,FA_OPEN_EXISTING| FA_READ); build ok ,it not run ok on the board. I try to debug it ( keil v4), i see the state pointer go into loop that’s HardFault_Handler . I do not understand what is happening, can you help me?
    sr! my english is not good.
    This is my code:

    int main(void)
    //Fatfs object
    FATFS FatFs;
    //File object
    FIL fil;
    //Free and total space
    uint32_t total, free;
    //Initialize system
    GPIO_SetBits(GPIOD, GPIO_Pin_14);
    USART_SendData(USART2, ‘1’);
    printf(” Cau hinh thanh cong r”);
    //Initialize delays
    //mount drive
    F_FRESULT = f_mount(&FatFs,””,1);
    printf(” Mount success r”);
    F_FRESULT = f_open(&fil, “ABC.txt”,FA_OPEN_EXISTING| FA_READ); //if remove this line, its success runs.
    if(F_FRESULT==FR_OK) printf(” open file success r”);
    else printf(” not open file”);

    • nikhil

      try by increasing the stack size

  • marco_aurelio

    Hello Majerle,

    i´m having lots of problems with _weak functions in many libs that you provide under IAR environment. i tried to use ‘#define __weak __attribute__ ((weak))’ in ‘define.h’ but don´t works. thank´s for any help and knowledge that you can share! 😉

  • Klio

    Hi Miguel,

    Thanks for sharing this example. After disabling LCD and the gyroscope through the CS pin (both connected through SPI5) I got your example working on the STM32F429IDiscovery using SPI 😀 However, I can’t seem to get the LCD and SD-card to work simultaneously, I hope you could help me.

    I initialize the SD card (successfully), disable the SD-card by the CS pin and initialize the LCD successfully . Now I to disable the LCD by it’s CS pin and try to communicate with the SD-card again. It doesn’t seem to work anymore. Using an other order (initializing the LCD first) doesn’t work either, the SD-card won’t even initialize. The SPI settings of the LCD are the same as the SD-card, so that can’t be it.

    I tried using SPI4, pinpack1, since this unused on the board. No response either. BUT when I physically connect pins from SPI4 with SPI5 it works again (even though SPI5 is unused). Once it worked I can disconnect the pins between SPI4 and SPI5, press reset button and will keep on working (on SPI4), however, when I physically disconnect and connect the power source I have to connect SPI4 and 5 to get it to work again.

    I’m struggling with this for days , I really hope someone knows a solution. I use this board directly connected on the SPI-pins: .

    Thanks in advanced.


    • Hi.

      I think, that you have problems with your CS pin.
      By default, in SPI mode, CS pin for SD card is PB5, but this pin is used by external SRAM on discovery board, at least I think.

      Try to set another pin, check files for manually see which pin is available.
      You can’t use pins which are set in files for LTDC and for SDRAM.

      • Klio

        Thanks for the quick response. I used C3 as CS pin getting these results (which is a free pin)

        • Ok, then here is something strange.
          Can you send a project that I can check on it?

          • Klio

            This project (which is your example modified), that tries to Initialize the SD-card over SPI(4). This code only succeed if I connect E6-F9, E5-F8 and E2-F7.

          • According to your project, I can’t say anything because main.c is really fail written.
            I will take a look when I come home to test with F429-discovery board.

            Btw..update libraries.

          • Klio

            Thank you 🙂 ! Sorry for the messy code in main.c , it’s code to turn of/off led of the discovery board. The main() function should be quite readable! I will update to the new library, haven’t been on your website for quite a while,that’s the main reason why I haven’t update yet.

          • Why is CS pin configured as input without pull resistor?

            At least 4 mistakes I see here. All devices are active, with CS = LOW


          • Klio

            You are right, I initialized the CS pin the wrong way. I fixed this. LCD is however an exception, active CS=High and nopull (copied from it’s original working driver code)! The code still doesn’t work 🙁 (see ). It still works when I connect SPI4 and 5 and make the gyroscope active the first try initializing the SD-card, then disable the gyroscope the second try initializing the SD-card . (see the modified main.c )

  • Glen

    Hi Majerle, once again thanks for the awesome libraries!

    I have the FatFs for SDIO up and running great. I am just trying to optimise the speed that I am writing to the microSD card at.

    I already found you were limiting the transfer speed to 400kHz with:
    #define SDIO_TRANSFER_CLK_DIV ((uint8_t)0x76)

    So I have changed to:
    #define SDIO_TRANSFER_CLK_DIV ((uint8_t)0x00)

    This allow the SDIO CLK to run at 25MHz. I am writing blocks of 4096 bytes and achieving ~ 400KB/s. This seems much slower than the indicated speeds of ~7MB/s on ST forums. Writing larger blocks doesn’t seem to help.

    Do you have any suggestions for how to optimise FatFs / SDIO to write faster. My goal is to write one file ~600Kb as fast as possible i.e under 30ms.

    • This is 20MB/s, which is inpossibke for my opinion with fatfs and stm.

      • Glen

        I hadn’t worked out the rate but yes it seems it is higher than possible. At least I want to achieve the ~7MB/s others have got.

        Do you have any suggestions for this?

      • Glen

        I have managed to achieve 3.2MB/s by formatting the SD card as FAT32 16KB clusters. And using f_write() with block sizes of 16384. I have heard that formatting with SDFormatter improves speed again. Unfortunately I am unable to use this with my SD card (incompatible error which is strange). Other option is to format using the Chan FatFs f_mkfs() onboard.

  • Tassilo H.

    Hello Majerle,

    first thank you for providing these libb, which helped a lot to get started on the STM32F407.

    But I have found a problem that will only show under certain circumstances when using DMA transfers with the SDIO interface, but then will lead to corrupted files.

    The issue comes from the way the DMA is set up (which probably comes from the original code from STM). In the functions

    void SD_LowLevel_DMA_TxConfig (uint32_t *BufferSRC, uint32_t BufferSize) and
    void SD_LowLevel_DMA_RxConfig (uint32_t *BufferSRC, uint32_t BufferSize)

    DMA is set up to use a memory access width of “word” and a DMA burst of 4 transfers.
    This leads to certain limitations for the data buffer when a sector is read or written to the SD-card:
    The obvious limitation is that now a 2-byte (word-aligned) address is required for the sector buffer. Normally, this is the case with the memory layout of fatfs, but there is a problem when reading files in chunks of 512 bytes or more with the f_read/f_write functions to a buffer address that is not word aligned, because fatfs will then try to do the sector reads/writes directly to or from this address (bypassing its internal sector buffer), which fails (gives 1 missing byte at block start/end) .
    The second (even more tricky) limitation is, that according to the data sheet each DMA burst (of 2*4 = 8 bytes in our case) must not cross a 1k address boundary (I stumbled over this when a file read from the SD card was missing 2 bytes at the beginning when read at one place of my code, but was ok at a second place). To be sure of this, each buffer that is used for file access now should be 8-bytes aligned, which becomes a bit impractical.
    So I suggest to change the following lines in the above mentiond functions in fatfs_sd_sdio.c:
    // from SDDMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Word;
    // to
    SDDMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
    // from
    // SDDMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_Full;
    // to
    SDDMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_HalfFull;
    // from SDDMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_INC4;
    // to
    SDDMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single;

    This now allows arbitrarily aligned buffers by doing single-byte memory accesses. One drawback is though that this could lead to performance issues or DMA FIFO overflow when further heavy DMA load from other peripherals is going on during the SD-Card read.

    I hope this is useful,

    best regards,


  • Peter

    Hello Majerle!

    I’m trying to adopt your great work to my STM32f205 and I found a problem where:

    if (SDIO_GetFlagStatus (SDIO_FLAG_RXDAVL) != RESET)
    *(tempscr + index) = SDIO_ReadData ();

    Status of SDIO_FLAG_RXDAVL is always RESET and infinite while loop is executed without taking breath.

    I’m using 2GB microSD with SD adapter formatted in FAT32.

    Any idea? Please help.


    • Hum, I think you should look at reference manual for F2xx as I see you use this.

      • Peter

        I have checked reference manuals of F2 and F4 and there is no difference in SDIO.

        After 4 days of analysis of code I have discovered what was the problem, so I think it is worth to share my experience because many people in the internet had the same problem.

        Wires were too long! 🙂

        Thats all.

        • Ouhh, that may be true yes. Also, pullups can be the one who fails for communication.

  • hari


    When I used your code , i’m getting this error, what might have gone wrong?

    ..tm_stm32f4_delay.h(130): error: #77-D: this declaration has no storage class or type specifier __STATIC_INLINE void Delay(uint32_t micros) {
    ..tm_stm32f4_delay.h(130): error: #65: expected a “;” __STATIC_INLINE void Delay(uint32_t micros) {
    ..tm_stm32f4_delay.h(162): warning: #12-D: parsing restarts here after previous syntax error while (amicros–);
    ..tm_stm32f4_delay.h(164): error: #169: expected a declaration }

    • Hmm, which IDE you use?

      __STATIC_INLINE is “standard” declaration in cortex header files.

      • hari

        I’m using Keil v.5 and I have installed the CMSIS also

  • YoungJoo

    Hello Majerle,

    First of thanks for your great LIB!
    I tested in SDOI 1 bit mode and OK, works fine!!
    However if test in 4 bit mode, just mounted and then waiting ….
    I used your pin connection.
    I just want to get a hint where and how to check, so would you give me short hint ?

    many thanks

    • Check for all cables length, no pull ups are needed. Then it should work!

      • YoungJoo

        Hello Majerle

        According to your answer I changed the cable length and it worked !!
        I shorten the length from 22cm to 5cm and removed pull ups.

        many thanks !!!

  • Tomasz Mankowski

    Works like a charm! Thanks Majerle! Thanks Chan!

  • hari

    Hi Majerle,

    I modified your code and implemented support for SPI DMA. I was able to do the write operation using DMA properly (written 10k data to a file usng f_write), but in read opearation I’m seeing some bit errrors in my read data.

    Any idea about what might be going on?

    • Then I think you didn’t properly implement disk_read function.

      • hari

        All that I have to do is to just to edit the function TM_SPI_ReadMulti(FATFS_SPI, buff, 0xFF, btr); right?

        This function calls TM_SPI_Send multiple times where as in DMA the whole data (512 bytes) is read at once.

        Is there something that I’m missing?

        • Did you enable RX DMA for SPI?
          You need TX and RX

          • hari

            You meant .. DMA_Init( spi->, &dma_init ); and SPI_I2S_DMACmd( spi->port, SPI_I2S_DMAReq_Rx, ENABLE ); ?

            I have used this and the DMA code works fine(tested with another device)

            I’m able receive some read data but it’s having some bit error’s , that’s the issue…

          • Hum, i don’t know from my head right now what can be a problem.

          • hari

            I’m using this along with FreeRTOS , so do I need to edit any macros in ffconf.h ?

          • Make sure, fatfs has _FS_REENTRANT set to 1 for your RTOS.
            For more settings regarding RTOS, look at fatfs forums

          • hari

            When I try #define _FS_REENTRANT 1, I’m geeting error on _SYNC_t …. Actually I didn’t understood what _SYNC_t HANDLE really means… (I’m using freertos)

          • I’m not using FreeRTOS, so I really can’t help you here.
            In RTOS, you just have to make sure that you have reentrancy or you can get serious problems.

          • hari

            Tilen I’m now using your current library file and when I compile I get an errror ” Undefined symbol ff_convert (referred from ff.o).” where is this defined?

          • Inside “option” folder is stored.
            You need these in case you have _USE_LFN more than 0.

          • hari

            And about this error
            ……..LibrariesCMSISIncludecore_cm4.h(1071): error: #20: identifier “IRQn_Type” is undefined ?

          • core_cm4.h file is missing in your project.

          • hari

            At which portion are you switching from SPI low speed to SPI high speed.. for data transfer?

  • Rohit Warule

    Hi everyone ,

    am i working on stm32l1 discovery kit ,want to interface micro sd card to this kit for storing some bytes of data ….can we use the same libraries for L1 series ……..

    and one more i need #include “tm_stm32f4_disco.h” file for this

    i have searched for this file but i didn’t get this ……

    Thanks in advance ….

    • You can delete this include.

      Well, for L1 you will have to change SPI functions, or SDIO if L1 has it.
      Then you are able to run it.

      • Rohit Warule

        Thanks for your reply ,
        actually i am working on stm32 first time ,can you please tell me how can i interface SD card to this kit ,can you share any demo code using fatfs for the same so i can start working …………..i have tried it using the SD libraries but did not get any solution ……..

  • Nishu

    Hi Majerle ,

    i am using SPI3 for this project, i included all files which are mentioned here. And in compilation there is no error. But codition :

    if (f_mount(&FatFs, “”, 1) == FR_OK)
    is not getting satisfied.

    My connection for SPI with SD card are as mentioned :

    Pin 2 : CD/DATA3 : PD0 { Used as detect pin}
    Pin 3 : Command/Answer {Used as MOSI}
    Pin 5 : CLK {Used as Clock}
    Pin 7 : DAT0 { Used as MISO}
    Pin 8 : DAT 1 {Used as CS}

    But in defines.h i didn’t use write protect and Detect Pin.
    And in defines.h i used :

    /* Use SPI communication with SDCard */
    #define FATFS_USE_SDIO 0

    /* Select your SPI settings */
    #define FATFS_SPI SPI3
    #define FATFS_SPI_PINSPACK TM_SPI_PinsPack_2

    My Main.C is copied here, Please check once.

    Thanks for any kind of help in advance.

  • hari

    I use DMA mode for sector read, I can read single sector ie; CMD17 perfectly but reading multiple sectors continuously ie;CMD18 returns me an invalid/erroraneous data ,
    any idea about this issue?

    • Sounds interesting.
      What is returning you invalid data? DMA or CARD?

      • hari

        I assume it’ll be CARD,
        since the DMA code is tested already for our FPGA interface,which was working fine..

        • Ok, then it is card problem.
          I have no idea what could be from card.

          You can ask on fatfs forums.

      • hari

        Do I need to modify any FAT FS functions for doing the multi block read?

  • Ednucatio Matters

    Nice codes, thanks for these libs.
    I use this code in default SDIO 4bit mode.

    Here, PC10 is used as SDIO_D2.
    I also interfaced LCD with this.
    In 429Discovery board PC10 is used as LCD_R2.
    So, I thought it might create conflict. But it doesn’t! And worked fine. How?
    Can you please explain?
    Thank You very much,

    • It looks like it works.
      Probably, you have one RED signal less and bad red colors 😀

      • Ednucatio Matters

        I see :).. Thanks..

  • Petr Machala


    I would like to ask you guys about your opinions regarding mounting of the SD card…I have an application where I very rarely put a few lines of text to SD card plus I dont have a card detect pin and I was wondering what is a better solution for me…rather mount the SD card before every transmision or mount the card only once by user (for example like in Android) and leave it like that…thanks for your responses…

    • HI Petr,

      definetely is more risky to mount it one at a time and have it mounted all the time.
      But, you can also open file and do your stuff, then use f_sync() function to flush data to card but file will still be opened and data stored to card.
      Check FatFS manual for this function.
      I think this is what you want.

      • Petr Machala

        Yeah mount the card every time before the data transfer would be probably better and even easier…thanks for your reply…

  • Petr Machala

    Why is it possible to have a file name of only 8 characters? Why not longer?

    • Fatfs related. But it is possible. Google for fatfs lfn or long file names. They are disabled in my lib for fatfs options.

  • hari

    Hi , When I used this alongwith RTOS , my patform is getting restarted after some time, eventhough my read/write/moun/unmount operation is successfull.
    Any idea about what might be happening?

    • No, try to ask on fatfs forums.
      You can also try with debug, I don’t know what happens in your system 🙂

  • hamed_m

    Hello Majerle,
    i use fatfs SDIO 4-bit mode and i read at about 600KB/SECOND
    i need read high speed. can you help me?

    • Using this library and f_read function with 10kB STM buffer for read, I go to about 4MB/second which is pretty much maximum what my card support.

      So problem is: small buffer read size or your SD card.
      Performance depends on how many data you want to read with single f_read call.

      • hamed_m

        my code:
        uint8_t FrameData[PicLevel][8192];

        PicLevel = 15;
        WidthHeight[0] = 16
        for(j = 0; j < PicLevel; j++)
        for(i = 0; i < WidthHeight[0]; i++)
        f_read(&DFile, &FrameData [j][i * 512], 512, 0);

        • How you count your time to measure speed?
          Try to increase from 512 to max as possible, like 8192 as much as your buffer is.

          • hamed_m

            this code run in while(1) and GPIO_ToggleBits(GPIOB, GPIO_Pin_10)
            monitoring whit osiloscop F = 2.5Hz
            when increase 512 dont work Correct and also F = 2.5Hz

          • I will try now one “fix” and you will report to me if it worked OK for you.
            Please contact me via my email.

          • Try to redownload library and try with more than 512 buffer size.
            I’ve made some work on this problem where I think it might happen.

          • hamed_m

            redownload and test but now dont Mount

          • Hmm, strange.
            I reuploaded old version.

          • hamed_m

            Hello Majerle,

            This version also dont Mount

          • hamed_m

            I solved, change
            SDDMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;//DMA_MemoryDataSize_Word;

            in function SD_LowLevel_DMA_RxConfig
            in file fatfs_sd_sdio.c

  • Leonardo Garberoglio

    Can you, please, tell me how do I need to do to make a System Workbench (eclipse) project to test uSD over SDIO? I’m using nucleo 411re

    • Hi, im not using eclipse so i’m afraid I cant help you here.

  • amin

    thanks man

  • Letitia

    Hello Majerle ! Thanks for your sharing.I have some problems when wrting files when iwrite a file to the device,it will produce ten new files.I donnot know why.and sometimes when I give the device a command via i a serial will show garbled code

  • Tomasz Urbaniak

    Hello Tilen,
    I managed to get PinPack_1 for SPI1 to work. However, the behaviour of the SD card is still not predictable. Sometimes it works, sometimes not.
    When I examine the logic analyzer, I see that the card responses differenly each time. What could be the reason?


    • That’s definitelly strange.
      Do you use SDCARD proper?

      Mount, open, close, unmount?

      • Tomasz Urbaniak

        Yes, I’m using the Fatfs example from this site. I also uploaded the code to my second discovery board and it didn’t work either. Could it also be caused by the kind of wires I’m using? I cut arduino connectors to the length of 6 cm. The SD card socket is mounted on a piece of breadboard and attached to the discovery board with those short wires.

      • Tomasz Urbaniak

        hello Tilen,
        One important observation: the fatfs example does not work right after I plug in the discovery board. However, when I press the reset button for a longer time, the two LEDS (green and red) go on. But there is something more: it only works while I’m touching the PE3 pin!. This behaviour occurs on both discovery boards I have. And it only this PE3 pin. I’m using SPI1 with PinPack_1. It’s puzzling me more and more but at least I can reproduce this behaviour.


        • Definetely one problem can be here.
          You hardware. How does your board with microsd set up?

          Maybe you can add a little delay before you try to mount to allow SDCARD to get stabilized voltage.

          • Tomasz Urbaniak

            I’m using an SD card actually (not microSD). But look – I found this interesting paragraph on the website
            If you’re having issues with
            the SD card not initializing correctly, please ensure that you connect a
            pull-down resistor to PC5 (card detect line) and a pull-up resistor to
            PE3 which is the chip select line for the LIS302DL/LIS3DSH
            accelerometers, otherwise those devices will interfere with the SPI
            So the strange responses from the card were most probably additional bytes from the accelerometer. Sometimes I was getting streams of bytes, which differed each time.
            I’ll try the resistors tomorrow and let you know.

          • But this configuration from elia’s web is for his SPI settings, not for my.
            Read carefully about that.

            Try to change SPI settings for testing.

        • Nino Gross

          I have exactly the same problem! Making a connection from PE3 to 3V helps in this case.

  • Tomasz Urbaniak

    Hello Tilen,
    Is SPI mode sufficient to read and play wave files from an SD card (44100 sample rate, 16-bit), or should I rather use SDIO?

    • Try to always use SDIO if possible.
      Higher speed, less wasting of time.

  • Mat

    I have found information, that FatFs requires clock signal, which is generated by interrupts every 10ms. Is that true? I am asking, because I can’t find it in your library.

    Best regards,

    • No, its not true. You dont need any reference clock because this is not usb/ethernet etc where data can come anytime. In fatfs, data are read/written when you need.

      So no, no need.

  • Jonathan Metz

    Hello Tim,
    First of all: great libraries; thank you very much for that. I am beginner with STM platform.
    I am trying to write sd card library with HAL drivers, using eclipse ide. At the moment i get strange error: f_mount doesn’t return any value. Have you got any idea why? And the second question is if you are going to make some tutorials with HAL drivers?

    Best wishes

    • Hello Jonathan,

      1. I don’t know how is your low level driver for SDCARD implemented (probably SDIO from HAL drivers)
      2. I won’t do any HAL tutorials. STD drivers are just fine for those who knows what are doing with MCU.

      Have a nice day 😉

      • Jonathan Metz

        Thank you for reply. I am using SPI. Situation is strange for me, because f_mount doesn’t execute any operations on the sd card. Is that mean, that there is problem with FatFs?
        Here is my testing code:

        if (f_mount(&FatFs, “”, 1) == FR_OK)

        And there is no reaction, which means, that f_mount returns nothing.
        Am I miss something?

        Have a nice day:)

        • I don’t know how your implementation (low level) looks like.
          I don’t use HAL drviers with their implementation so I have no idea what to do.
          You can use my lib to test and stop using HAL drivers.

          • Jonathan Metz

            Thanks once more 🙂
            I will run some tests, and I will let you know, if there will be some positive results.
            Keep calm and use Tilen’s libraries 😛

  • Simon


    I want to use your libs with freeRTOS but I’m running into a problem that your SysTick_Handler function in tm_stm32f4_delay.c overlaps with freeRTOS functions. I was not able to find where the function is called, so that I can just rename every thing. Do you have any idea how I can work around this?

    Best Regards

    • Take a look at my DELAY library, how to setup custom timer for delay functions. When you enable one of many timers in STM32F4xx device for DELAY, SYSTICK timer becomes free and ready for RTOS operation.

      • Simon

        Thank you that helped 🙂

  • Mohammad Kamel

    hi i want to do this job with spi protocol first i exactly did what you said in article and i didnt use rtc when i download to my board and use debug when i arrive to if (f_mount(&FatFs, “”, 1) == FR_OK) ((LEAVE_FF(fs, res);)) the debaging stop and nothing deosnt happen what should i do . i use memory 4 GB with FAT16

    • Why you use LEAVE_FF(fs, res); ?
      This is fatfs related.

      • Mohammad Kamel

        i dont use it it is your library i exatly use your code but in f_mount function when arrive to LEAVE_FF(fs, res);
        my code stop working

        • How you mean your code stop working?
          Do you get hardfault or something?

          • Mohammad Kamel

            when code is excuting (f_mount(&FatFs, “”, 1) == FR_OK)
            evrything stop and wont excute f_open or anything else

          • Send me a project to my email.
            Don’t ask for email, search for it.

          • Mohammad Kamel

            thank you alot i will send it to you thanks alot 😀

          • kaitek_91

            Hello, my project also goes into HardFault loop (on debug it stays in res = find_volume(&fs, &path, 0);) – I tried in SDIO4bit and SDIO1bit – what could be wrong?

          • Make FATFS structure global instead of local.
            FATFS fs.. //make this global

          • kaitek_91

            Thanks – mounted OK (Red LED ON) but it doesn’t go into “if (f_open(&fil, “1stfile.txt”, FA_OPEN_ALWAYS | FA_READ | FA_WRITE) == FR_OK)”.

          • Then do FIL fil; global also.
            Format SDCARD as FAT16 for testing first!

          • kaitek_91

            FIL maked also as global and MicroSD 1GB formatted as FAT16, but still doesn;t go into “if (f_open(&fil, “1stfile.txt”, FA_OPEN_ALWAYS | FA_READ | FA_WRITE) == FR_OK)”. Keil can’t debug using breakpoints inside f_open…

          • Try to be creative and check which error f_open function returns to you. Maybe you don’t have enough HEAP memory for long file name allocation. Check return statement and report it to me.

            Below are all possible from FATFS:

          • kaitek_91


          • You are able to find solution on FATFS page without me!


            Increase HEAP memory in your project or use other _USE_LFN option value.

          • kaitek_91

            Thank you for fast replies and sorry for my lack of creative thinking. I decreased _MAX_LFN to 127 and it works.

  • Mohammad Kamel

    excuse me i realy confused what i should do ????please help me

  • Mohammad Kamel

    hi thanks for helping me yesterday i did the project with sdio and i got answer but i changed my SDcard and it doesnt mount could you tell me what is its FAT format and allocated size for SD card thanks alot

  • Simon


    I am still trying to get the driver to run with freeRTOS and I dont know what else to try. The driver gets to the part where wait_ready is called but this always returns a timeout. I want to use SPI and my defines.h looks like this:

    #define FATFS_USE_SDIO 0
    #define FATFS_SPI SPI1
    #define FATFS_SPI_PINSPACK TM_SPI_PinsPack_1
    #define TM_DELAY_TIM TIM2
    #define TM_DELAY_TIM_IRQ TIM2_IRQn

    Several SD-Cards did not work with this setup, and I dont know where else to look for errors, do you have an idea what else I can try, or is it most likely a hardware error?

    Best Regards,

    • Hello Simon,

      which error does f_mount() function returns to you?
      FRESULT fres = f_mount(…..);
      print this fres somewhere or use debugger to check it’s value.

      Definetelly there could be hardware problem with SPI or CS pin. Check CS pin as well if it is correct.

      • Simon

        The return value of f_mount is FR_NOT_READY and I checked the pins, they are as described in you pinout table.

        • hari

          You should check your IRQ mapping is correct .. then you have to reduce the theTimer interrupt preemption priority to min vaue ( i had to make it 0x0F) .

          • Funny, because I dont need any of that to do and it works everywhere for me.

            Butif this solution works for you, ok. I can live with that.

          • Simon

            How do I know if the IRQ mapping is correct, and where do i find that interrupt priority?

          • Please don’t give non-real advices. There is no need to do anything.
            The point of everything here is that you hardware has some issues.

            This software is running on several projects without any problem.
            Make sure you have correct wiring, and short wires. 5-6cm.

          • Simon

            Hi Majerle,

            to confirm that its a hardware error I tried to run your driver in a project without freeRTOS. I also downloaded all library’s new and noticed that the tm_stm32f4_delay.c changed (+ 100 lines). But now I there is a new problem with the line 224 in tm_stm32f4_delay.c irq = __disable_irq();
            fails to compile because the function __disable_irq() is defined with a return value of void.
            The function is defined in core_cmFunc.h at line 330. Is there a newer version of core_cmFunc.h? I tried to used the one I found in you github repository.

            Best Regards,

          • __disable_irq() according to the ARM documentation returns current IRQ status.
            You are free to delete “irq =” before __disable_irq() is called.

          • Simon

            It realy was a hardware error, got a new sd card module today and now its working.
            Thank you for all your help 🙂

          • Nice to hear that it works. Have a nice and successful use 🙂

  • hari

    Hi Tilen,

    I used your code and was able to get the SDIO working , but when i tried to check the throughput, i found that it takes 6.08ms to write 1539 bytes , which gives the result of
    (1539*8bits)/(6.08ms) = 1Mb/s , which is very much low…

    Shouldn’t the SDIO interface give a high throughtput..

    I used #define FATFS_SDIO_4BIT 1

    • Hello,

      This depends on card perfornance and data align you wanna write.
      Look at fatfs for more info.

      Try to write a multiple of 512 bytes, so instead 1539 write 1536 or the next align of 512.

      • hari

        Hi I used Kingston SDHC 16BG Class 10 SD card,
        So I tried writing 2048 bytes

        if (f_write(&fil,data_buffer,2048,&written) > 0)
        GPIO_ResetBits(GPIOD, GPIO_Pin_4);

        And found that now it takes 3.772ms , so gets 4Mbits/sec,

        But in your previous comment I found you got MB/s , what else do I need to take care to achive that much throughput..

        • When I tested this I had 10k buffer.
          Btw..that was for reading, not writing.

          Having 512kB/s is quite nice for write.

          • hari

            So I used the read

            GPIO_ResetBits(GPIOD, GPIO_Pin_4);

            I was able to read 10240 bytes, in 2.904ms , which gives

            10240/2.904ms which gives 3.5MB/s …which is excellent..

            But I want the writing also to be done at faster rate… Please help me with your suggestions ??

          • hari

            Also the CLK I see is 33Mhz , can we increase that to higher rate ?
            and I see that SD_HighSpeed() function is not being called anywhere.. can I use it for high speed?

          • Block size is 512B I think. Depends on your card but 512 is ok.
            Second thing,when you read is also 33MHz clk?

            You can try with high speed.

          • hari

            Hi Tilen, any solution for this?

          • I think you wont be able to get more.
            Writing is obvious slower than reading and it looks like that you card can’t go faster.

            Thats my opinion. I hope I am wrong here.

          • hari

            Tilen, sorry if I’m bothering you… can you please runa quick write test on your setup and let know the result,?

            I got read of 3.5MB/s… which is great

          • 3.5MB read or write?

          • hari

            3.5MB/s for a read of 10240 bytes..

          • What you wanna do here?
            I told that I got 3.5MB and you have it too. So what should I do here? 😉

          • hari

            How much did you got for the write speed ??

          • Just for you my friend 😉

            Here is code:

            PS: SD card is provided from ST, I have no idea which class it is.

          • hari

            Hi , Tilen ,,,, Thanks friend.. for your patience and support…
            I debugged the code to small extent I could see that some times the function TM_FATFS_SD_SDIO_disk_write(); is called more than one time, at that time i gets low throughput, otherwise when that function is being called single time I get a good throughput..

            Any idea what could be the reason …? Is some kind of timeout happening so that TM_FATFS_SD_SDIO_disk_write() is called again?

          • You see?

            When you don’t have proper align of data to send at location, check where you have & 3 checking in if statement and then while loop.

          • hari

            Ok ,so I put a break point at the line DWORD scratch[BLOCK_SIZE / 4]; and created the environment where 2 times the function was called.. but the breakpoint didn’t got hit..

            So that if statement wont be causing issue,, else what can cause the behaviour?

          • Maybe fatfs calls function multiple times.

          • hari

            Hi Tilen, found a bug in th fatfs_sd_sdio.c file

            in SD_ProcessDMAIRQ() , if we are using DMA2_STREAM6 we have to CLEAR DMA2_HISR flag, where the code clears DMA2_>LISR for both stream3 and stream6,

            Please update this in your code…

          • Dont use this stream then 😉

          • hari

            Hi Tilen, wanted to ask something more 😀 ,,,,

            In the SD_WaitWriteOperation (void) I can see a timeout while loop which just counts down If I’m planning to implement this using hardware timer what should be the timeout value expected ?

          • Why waste one timer for something like that? Are you making professional lib? 😉

          • hari

            I,m using this in my project which is litlle time critical 😀

          • Again..why timer?
            You know what timeout feature means? If yes, explain here please.

          • hari

            Forgive me.. :P, that was not needed, wouldn’t give me better performance in multitasking environment

  • Michał Biolik


    I’m trying to use your example 21-STM32F429_FATFS from Github. I want to use SPI communication so in defines.h i made changes:

    #define FATFS_USE_SDIO 0
    //not sure if whats below needed
    #define FATFS_SPI SPI1
    #define FATFS_SPI_PINSPACK TM_SPI_PinsPack_1
    #define FATFS_CS_PIN GPIO_Pin_5

    In main.c I also added line :

    TM_SPI_Init(SPI1, TM_SPI_PinsPack_1); //also not sure if needed

    But unfortunately it fails. I worked out that f_mount returns FR_NOT_READY instead of FR_OK.

    I use sd hc card with FAT32. Can you help me somehow ?

    • Hello,

      for your SPI, you have to use then PA5, PA6 and PA7 pins. Make sure also that you have included files for SPI drivers, so file fatfs/drivers/fatfs_sd.c and .h file.

      You don’t have to init SPI by your self.

      • Michał Biolik

        I took me long time, but I just figured out that is good idea to check it with another card. And of course it helped 😉 Thanks !

  • Karthik

    Thanks for sharing this nicely written library code and keil projects. I am able get this project working on STM32F4 discovery and STM32F411 discovery boards. I just had one issue: My heap size of 0x200 in (board)_startup.s was not enough. Increasing the heap size to 0x2000 in (board)_startup.s fixed the heap allocation issue.

  • Prabhu Chawandi

    Hi Tilien

    Can you point me what filesystem to use if I cant use SDIO, I have to use one SPI NOR FLASH

    I cant use SDIO, as those pins are used for other purpose, I was thinking if any small filesystem be crated on NOR FLASH. I need to access some images from my program.

    Many Thanks,

    • Technically, files for SPIFLASH (NOR, NAND, whatever which) are created in my fatfs library under fatfs/drivers folder.
      You will have to add communication for you NOR FLASH chip and then, in your program, you can do this:


      So, device name to use for your SPI flash has name SPIFLASH:

      You just have to make structure for disk read, init and write for your FLASH according to it’s datasheet.
      You can see how I did it for SDRAM in STM32F429-DIscovery board, which principle I used.

      • Prabhu Chawandi

        Thank you for the Quick Reply. I will use your library.

      • Prabhu Chawandi

        How Can I pre-load files to this filesystem created over SPI NOR ? I have some images, which I want to store in this FS. I can build then as part of my process after converting to bitmaps, but RAM would be eaten unnecessarily.

        Many Thanks,

        • You definetelly need to upload images to STM flash first and then read flash and send to SPI NOR using f_write function. I don’t see other options.

          When you do this, you can then clear flash on STM and you are done.

  • Anton Khrapov

    Hello Majerle,

    Do you have any experience with interfacing CF cards to stm32?

  • mukhe

    hey TM,
    thanks for the library

    I am trying to compile the library but i got couple of no prototype errors. I cleared out half of it by declaring the function on the c file however I am not sure how i should approach solving these no-prototype errors

    Error[Pa045]: function “clust2sect” has no prototype
    Error[Pa045]: function “get_fat” has no prototype
    Error[Pa045]: function “put_fat” has no prototype

    these are from the ff.c from Chan’s library

    • Hello,

      which compiler you use? I never saw Error[Pa045] before in Keil or GCC.

      References should be in ff.h or ff.c files.

      • mukhe

        IAR Workbench

        hmm..i did look for those function but I am not sure whether i should just declare them or they should be declared under some condition

        • It does not reference because it is declared at the beginning on C file and this is compliant with ANSI C language. Function does not need reference (prototype) in case that is declared before it is first time called for compiler. In this case, it is declared first, and then (lower in file) it is called.

          But you can put references in the beginning of .c file for all functions you get errors. References does not make errors if there is no actual declaration implemented.

          • mukhe

            ok will do so, thanks

          • mukhe

            compiled, thanks

  • Michał Woźniak


    I’m tryung to launch library on Nucleo 411. I’ve downloaded all libs from github.

    choose target, compiled and loaded. Nothing happened.

    What I’ve observed:

    while (1) {

    that code blinks more frequent than once per second.

    Whats is wrong with timing?

    SystemCoreClock seems to have correct value – I compared with working projects…

    • Delayms(1000*1000*10); if this is more than one second, then:

      PLL is not correct or,
      Delay is not initialized.

      • Michał Woźniak

        /* Initialize delays */
        it is done.
        Delayms(1000*1000*10); it lasts about 800ms. It should be 10 000 000(ten millions)!

        I didn’t change anything else in the code.
        Could you tell me how to check PLL?

      • Michał Woźniak

        hello again,
        my SD card dont want to work.
        could you please load that example from github on your Nucleo 411 board and check the timings?

  • batman Simon

    in defines.h I just add #define FATFS_USE_SDIO 1

    so defaulf is using sdio 4bit

    but it not working .

    >> mount OK

    >> if (f_open(&fil, “stfile.txt”, FA_CREATE_ALWAYS ) == FR_OK) >> NOT OK

    • that’s baaad. And what is the problem here? What is return status from f_open function?

  • batman Simon

    Hi, Tilen.
    How i can fix error ?
    (17) LFN working buffer could not be allocated */

    • Increase heap memory, in compiler.

      • batman Simon

        How can fix it ! crease = ?. I don’t know. I using sdcard 2GB – fat32

        • like I said, INCREASE heap memory!

          • batman Simon

            Hi Tilen, so i need change value in code ?

          • I dont know which compiler you have, but on keil uvision, .s file is where you set heap size by settings variable in that file.

            For gcc, use google.

          • batman Simon

            Thanks You! Tilen.

            I Using STM32F404Vet but using file starup_stm32f40_41xxx.s.

            what I can using file .s with fit better.

  • Kyaw Kyaw Aung

    Hi TM,
    I just started trying STM32F4 Discovery board and your libraries has been a huge help for me. Thank you so much for that.
    For this particular code (that I got from your github), I have a tiny error.
    When I use “res = f_mount(&FatFs, “”, 1);” I get “res = FR_NO_FILESYSTEM (0x0D)” error. So, I use “res = f_mkfs(“”, 1, 0);” to format. But there’s a “res = FR_DISK_ERR”. How do I solve that Disk Error?
    Thanks in advance.

    • Hello,

      disk error is caused by low level problems, so is card inserted or something? Check FATFS documentation why errors are returned.

  • Bernard Bau


    First of all, thank you so much for your good work 😉

    I am using a STM32F401RE nucleo board. I have compiled the example code (no errors or anything) and also tried everything i can think off but the code seems to execute up until this point every time:

    //Mount drive
    if (f_mount(&FatFs, “”, 1) == FR_OK) {

    Upon further investigation in debug mode I saw that the microprocessor is stuck in this function:

    * @param Delays for specific amount of milliseconds
    * @param millis: Time in milliseconds for delay
    * @retval None
    * @note Declared as static inline
    static __INLINE void Delayms(uint32_t millis)

    Specificly, this while loop:

    /* Wait for timer to count milliseconds */
    while ((TM_Time – timer) < millis) {
    #ifdef DELAY_SLEEP
    /* Go sleep, wait systick interrupt */

    Any idea why it gets stuck there? I would really appreciate a solution to this problem…btw I am fairly new to STM devices.

    Thanx. And keep up the good work!

    • So you used directly my example?
      Have you also used directly my project, or you created your own and copy/paste main there?

      Option is that PLL is not set properly and it fails then.

      • Bernard Bau

        Thanx for the speedy reply!

        I used the keil default project and added all the necessary dependencies.

        • Let’s check, what is problem here.
          You can download my Github repo and open SDCARD project directly from there and test how it works.
          BTW: If you are using SDIO communication (default) then delay function should not be active at all. I mean, they are never called as far I know. (Maybe I failed) 🙂

          • Bernard Bau

            I was using SPI, because the SD car breakout module I am using has it’s pins named: CS, MOSI, SCK, MOSO and so on.

            To test it I quickly reconfigured so it would run SDIO 1-bit mode (not 4-bit because the breakout does not have enough pins). Its seems better now, although it has a problem with mounting the SD card now (in other words (f_mount(&FatFs, “”, 1) == FR_OK) does not return FR_OK.

          • What does it return? It is something funny, that your hardware works strange as mine.
            I tested this example on F401/F411 nucleo with external 8MHz clock provided from F103 mcu. There is one jumper which should be on for clock to be active. Check nucleo schematics.

            Or put it off, and use internal STM clock

          • Bernard Bau

            That might be the problem, because I didn’t change any jumpers. I am not sure which jumper you are referring to though, I checked the schematic quickly and it seems that the 8 Mhz crystal is connected to PF0/PD0/PH0-OSC_IN and PF1/PD1/PH1-OSC_out. The only things connected to those pins that I can change is SB55 (open), SB54(closed) and SB50(closed). To change those i need to solder them, but no jumpers?

          • Bernard Bau

            Also the return value seems to be FR_NOT_READY

  • George

    Have you ever tried to add a line to a text file?

    • Like enter button in text editors? I did.

      • George

        Thanks for the speedy response. I’m using your msc host library and can’t manage to add a line of text to a file. Each time it overwrites the data in the file. Tried f_sync, f_lseek and no luck. Any tips?

        Thanks in advance

  • Teodor Vasile

    Hi Majerle,
    I am really new in this kind of software. It is a few levels above compared to what I have done so far, but I am eager to make it work.
    I am using a STM32F427 VIT6 microcontroller, which is customly built on a circuit board and is having also a SD card slot.
    The connections correspond to the one you have posted above (for the SDIO interface), so I am pretty sure the problem is in my software. My goal is to write and to read from the SD card (e.g. .txt file). For the start I would like to check if the card is recognised by the uC.
    Could you describe me quickly the steps I have to do in order to make this happen? Could you give me a short code doing a writing and reading or adapt your code above in order write “hello” in a .txt file on the SD-card and to read “hello” from a .txt file from a SD-card?
    Where should I copy the files from your library?
    I am using a 2GB (memory capacity: 1,83GB), FAT32, Transcend uSD-Card – attached to an adapter to fit in the slot. Could this be problematic? The software I am programming in is called Em::Blocks 2.30.
    Thank you in advance for your answer! I really couldn’t find something concrete to this topic, thatswhy I am asking you for help.
    Best Regards
    Teodor Vasile

    • Hi,

      if you have the same SDIO pinout as I have, then download my Github repository for start and try Keil uVIsion example. Example for SDCARD should fit into 32kB free code where you can try it. You will be able to detect if card is detected. Example works, so if it does not in your case, you will have to check other things.

      Start this example first and report.

      • Teodor Vasile

        txs for your fast response.
        I do have a question regarding the pinning between uC STM32F427 and the SDCard adapter. Where may I find the code (in which file?) where the pinning and the routing of the PINs are described and determined? is this changeable? or they are fix defined routings of the uC?
        I am asking this because I’ve checked my circuitry plan and all the pinnings are good (the same as you have listed above) only the Card Detector PIN and the Writing Protection PIN are connected differently.

        • Card detect and write protect pins are not part of communication (SPI or SDIO).
          Functionality of these 2 pins is done totally in software, there is nothing hardware related to peripherals.

          For SDIO, check fatfs/drivers/fatfs_sdio and for SPI check fatfs/drivers/fatfs_sd files.

          Description how to change these 2 pins is described above.

          • Teodor Vasile

            Is your above described project working with the uC STM32F427 VIT6? – so I have only a the uC mounted on a custom made circuit.
            I did everything like you have mentioned above, but I get an error like – “Please select your board. Open tm_stm32f4_disco.h and follow instructions!!”. So I did so, but I couldn’t find my uC.
            Is there any WORKAROUND to make it work with my board?

          • You got this error, because my DISCO library supports different ST development boards.
            You can easily remove this library and LED functionalitites from code.
            Lib is for LEDS and buttons on discovery/nucleo/eval boards and that’s the reason why you have error because you are not using ST development board but your custom.

            Hope I was clear.

          • Teodor Vasile
          • Teodor Vasile

            I did the things you’ve mentioned. I still don’t know how to handle some errors which looks all the same:
            “In function ‘validate’: undefined reference to ‘disk_status'”
            “In function ‘sync_window’: undefined reference to ‘disk_write'”
            etc . . . every error refers to the file ff.c
            Could you give me a hint at this point?

          • Diskio.c is in project?

          • Teodor Vasile

            you’ve been right diskio.c was missing, thatswhy that error messages.
            Afterwards I’ve continued to add other libraries from Github – Espruino/targetlibs/stm32f4/lib/ in order to solve the error messages I’ve got. Now I’ve reached another set of errors like (see attach):
            “In function ‘FMC_NORSRAMDeInit’: error: ‘FMC_Bank1’ undeclared (first use in this function)” etc … – in the file stm32f4xx_fmc.c
            I don’t really know if my project needs more libraries or if I have to do smtg else?!

          • Looks like you ntbt have FMC in your device. Remove lib from project!

          • Teodor Vasile

            I have deleted stm32f4xx_fmc.c and stm32f4xx_fmc.h and got this error now.

          • You need SDRAM in your project? Really?

          • Teodor Vasile

            No I don’t think so. So I’ve deleted all the libraries which contained “..sdram..” in it and now I get this one:

          • Rcc lib is multiple times in project added.

            PS: make some research alone!

          • Teodor Vasile

            I still can’t make my code compile flawlessly.
            In the attach you can find my libraries:
            What should I add to it or delete in order to make it work? I can’t really understand how this work and which “Dependencies” should be added.
            Txs in advance for the answer!

  • Leo Cechet


    I am having trouble adapting FatFs to the STM32F105 MCU. The STM32Cube has the library for the evaluation board, however it uses HAL, which makes things very complicated for me to adapt to my own software. Have u already done this for the mcu I mentioned? What could be so wrong about it?

    • Hi,

      adapting this code with HAL is the most easiest ever! 🙂

      You can check my HAL library for FATFS and check there. I’ve made very simple low-level driver.
      Function you will need to check is probably in fatfs/drivers/sdio.c in libraries folder.

      Otherwise, problems can be with clock buses, pin configurations and so on.

      • Leo Cechet

        Ok, but I dont want to use the HAL Library. Do I need to use it? I just want to simply use SPI + FATFS. That’s all, but it doesnt work!

        • OK, what exactly does not work here?

          • Leo Cechet

            Well, it wont work as it should. It doesnt really mount the FAT drive.

            It says that fmt == 1 and then it goes into this routine:

          • Leo Cechet

            if (fmt == 1)

          • Leo Cechet

            The real problem is here: fmt = check_fs(fs, bsect = 0); I am using two different codes and it stops right here! I have a 2gb sd card in FAT16 (FAT only). The thing is that it returns FR_NO_FILESYSTEM.

          • Leo Cechet

            Any ideias?

  • Mihai Negoita

    Hello Marjerle,

    Thank you for your libraries. I have a STM32F407 board and I am using your fatfs lib with 4-bit SDIO interface to write on 32 G card. Everything works great. I am trying to change DAT1 from PC9 to PC14 or PC7 as I am planning to use PC9 for a clock signal to drive an external device. What I did, I changed GPIO_PIN_9 to GPIO_PIN_14 in TM_GPIO_InitAlternate call (in SD_LowLevel_Init function). Unfortunately this seems not to be enough. Is anything else I should modify to use DAT1 on a different pin than PC9? Thank you

    • PC14 does not have SDIO_CK capability.

      • Mihai Negoita

        I have tried PC6 or PC7, it does not seems to work either

        • I don’t see SDIO_D1 for you on these pins.

          • Mihai Negoita

            I checked the documentation more. Only PC9 can be used for SDIO_D1. Unfortunately MCO2 is also available only on PC9. So using SDIO and MCO2 together is not possible. I have to use a dedicated external clock (with a SPI or I2C interface) to drive my external device.

          • PA8 can also be used for MCO.

          • Mihai Negoita

            The one on PA8 is very slow, up to 16MHz. I need a clock signal over
            100 MHz

          • PA8 can output PLL clock. Check lib 40.

          • Mihai Negoita

            O.K. great, thank you very much

    • Teodor Vasile

      Salut Mihai,
      eu folosesc un uC STM32f427VI6 pe un circuit electric, creat pentru o aplicatie anume. Pe acest circuit este montat si un adaptor SD pe care as vrea sa-l folosesc. PIN-urile conectate sunt din pct de vedere Hardware corect (corespund descrierii prezentate: DAT0-PC8, DAT1-PC9 …etc). Am downloadat librariile pe care Majerle Tilen le recomanda in tutorialul sau in sa fara succes. Trebuie sa recunosc ca nu sunt un expert in ale programarii, in orice caz ceea ce vreau sa realizez este sa scriu si sa citesc de pe un card SD. Ai putea sa-mi dai tu cateva indicii cum as putea sa realizez asta? Aici in tutorialul lui nu sunt toate librariile necesare din ce am inteles, iar de pe Github nu am stiut care fisiere ar mai fi necesare (asa numitele Dependencies). Mersi anticipat pentru ajutor. As aprecia enorm.

      • Mihai Negoita

        Sure. The needed dependencies are all listed on the page. Did you setup an environment (IDE) where you can compile and debug successfully a simple program? Personally I like am emblocks which works great (free IDE for windows).

        • Teodor Vasile

          Hi, I am also using Em::Blocks for my project. Yes I do have a program(code) which I can compile and debug succesfully – this is also running flawlessly on my board. Next I would like to add the SD-card feature, as the connections are described like above, thus they are available. So my actual question is, what libraries do I need in order to have a program that works (that compile at least perfect) with the SD Card? Then I can come back I tell how it worked for me. Txs PS:like i have mentiones in the 1st msg I have downloaded all of the libraries that were mentioned in this tutorial, but honestly I couldn’t make it compile properly.

          • Mihai Negoita

            It’s good we are using the same IDE. What is your error message when compiling?

          • Teodor Vasile

            a lot of, because I have added libraries which maybe didn’t have to be added and so on. Could you name please all the .c and all the .h files I should download? Then I can make a try and tell you the errors I am getting

          • Mihai Negoita

            In the project folder I created tm_stm32fatfs folder.



            fatfs files you find them in fatfs library (library 21) and gpio files in gpio library.attributes.h you can find a link on this page for downloading

            You have to physically copy these files in the place mentioned before adding them from emblocks

          • Teodor Vasile

            I’ve copied all the files like you have described above. In the attachment you cand find a screenshot of my folder, containing all the files. Is it right? How should the main.c and main.h look like?Could you send me maybe these files?
            Then I could compile and see how it works 🙂

          • Teodor Vasile

            …small correction for the folder “inc”
            Do I really need ‘fatfs_sdram’ or “fatfs_spi_flash’ in the “fatfs”->”drivers” folder?

          • Are they mentioned in post?

          • Mihai Negoita

            No. I assume you are using SDIO, so fatfs_sd_sdio.c and fatfs_sd_sdio.c are enough. If you also copy


            in the tm_stm32fatfs folder you just created, and then add them in emblocks project -with file add you should be able to compile the main.c on this page (tm_stm32f4_delay.c and tm_stm32f4_delay.h are
            not really necessary if you remove the include delay include file at the top of main.c). The main.h does not matter, leave as it is. Try to compile and let me know the errors you get.

          • Teodor Vasile

            Hi, so I made this project work :). Very happy to see that .txt on the memory card with the textline in it.
            Now I would like to combine this one with my old project. I can’t really make it work. The thing I have observed is that my old project is using hal libraries. So I have acted like in the tutorial presented by Majerle in Library20 – Hal library and tried to get sd-card work with the hal libraries implicitly with my old project. I am stocked at this lines:
            iti pot trimite proiectul daca vrei. Poate reusesti mai repede sa-ti dai seama asa.

          • Mihai Negoita

            As far as I understood Marjerle’s libraries and HAL libraries they don’t work together because both use low level libraries (in a different way) so you have to choose one or another. Marjerle’s libraries are pretty comprehensive so you don’t really need HAL. I maybe be wrong, I never used HAL to be honest. I’ll have look at lib 20 when I get a chance.

          • Yep, that’s right. You can choose what is your option here.
            I personally suggest Standard peripheral drivers but they are (or at least will be soon) dead from ST side.

          • Mihai Negoita
  • George Waller

    Hi, I have got your code working on my STM32F407 discovery board but I get a disk error when the disk is read for the first time. So res = FR_DISK_ERROR in the ‘move_window’ function. I’m using 4bit SDIO with a multiple 2GB micro SD cards formatted with FAT(default) or FAT32 (tried both) in Windows. I’m using IAR workbench. I have checked the connections multiple times but they are good and I think it would have returned an error sooner if there was a connection problem. I get the same error with all cards. I wonder if you could suggest anything? Thanks.

    • George Waller

      Going further in the code I get a ‘SD_COM_CRC_FAILED’ when ‘SD_ReadMultiBlocks’ function is executed. Could some tell me what this means?

      • If CRC failed, then there are communication problems, meaning too fast frequency for too long wires.
        This is most common problem.

        • George Waller

          Thanks for the quick reply. I did indeed find that it was the SD card adapter that I was that was faulty. I have another which is now working but I can only use with SPI (on the back of a display) I only get a write speed of about 160kB/s with a 10kB block write. This is with ‘SPI_BaudRatePrescaler_2’ instead of ‘SPI_BaudRatePrescaler_32’ in your spi header file. Is there anyway of getting SPI faster? 1MB/s should be possible, no?

          • What about PLL settings?
            Is STM configured properly?
            With wrong PLL settings, you get wrong SPI speed and that may cause problems.

            BTW..when testing performance, use buffer size muptiple of 512. For example I used 100*512 bytes for testing and I got more than half of MB/s with SPI writing speed with class 4 card.
            With SDIO, this speed went up to 6MBytes/s.

          • George Waller

            So my SYSCLK is at 168MHz, PLLM divider was at 25 so I changed it to 16. I now have 780kB/s with 10kB write. Thanks for your help, your efforts for this site are remarkable. Well done!

          • PLLM should be set as your input clock. If you have 8MHz clock crystal, set parameter to 8. In case of internal RC clock, use value 16. Just checking 🙂

    • George Waller

      I have tried using SPI but this doesn’t work either.The ‘TM_FATFS_SD_disk_initialize’ function returns TM_FATFS_SD_Stat = 0x01. Due to this being a different setup and the fact I tried to get FATFS working with CubeMX mean it could be to do with the cards? I’m using a SD to micro SD adapter with a 0.1″ header soldered to the adapter – it’s looks in good condition. Then jumper wires about 150mm long attach it to the discovery board. Could this be an issue?

  • Zoltán Dudás

    Hello Majerle,

    I have a custom design with stm32f407, and I would like to use this lib of yours. But I encountered a problem, which I can not figure out. I am using the sample code above, but at f_mount() the result is FR_DISK_ERR. So I started to investigate using debugger, and I dig it until I found out, that I have SD_RX_OVERRUN TransferError (in fatfs_sd_sdio.c:SD_ProcessIRQSrc). I don’t know what could be the problem, please help me! I am using GCC, 4 wire SDIO, _USE_LFN = 1.

    Thanks in advance!

  • Jarosław

    I’m using STM32f407 and CoIDE. I tried to use Library 21 and SPI communication. Everything compiles well but in the end I always get FR_NOT_READY when I use f_mount. I even tried to check on the oscilloscope if SPI is working but I realized that at PA7 there is only constant 1. Can anyone explain what am I doing wrong?

  • K.Wanq

    Hi all,
    I’m using STM32F4113-Disco Board and SW4STM32.

    I met the error stated below when build project:
    In ccsbcs.c, Multiple markers at this line
    – multiple definition of ff_convert' & ff_wtoupper’
    – first defined here

    I checked ff.h and ffconf.h, the function prototypes are declared in ff.h. There should be no problem.
    Anyone met this error before? How to solve this error?

  • Kleber Lopes

    Hello Majerle, thank you so much for these libs!

    I am having two problems:

    1 – If I turn on the STM32 with the sdcard, the program runs normally (SD is recognized and I can read / write). But if the sdcard is already initialized and I reset the STM32, SD card is not recognized. I have to send a command to “return” the SD to the initial state? (He answer OK to CMD0 command but fails in others).

    2 -Cards with more than 2GB are not being recognized, what can I do?

    • Hi,

      What if you use directly my example from Github? Which board you have?

  • dev_sam

    i am trying this project on STM32F407 Discovery board with both SPI and SDIO. There is one problem that File is not created . If I create file earlier then the string is written in it.

    Again when i debugged I found that
    1. SDIO mode
    SD_Error SD_WaitWriteOperation (void)
    while ((DMAEndOfTransfer == 0x00) && (TransferEnd == 0) && (TransferError ==SD_OK) && (timeout > 0)) {

    2. in SPI MODE: return 0xff; is executed.

    TM_FATFS_SD_disk_initialize (void) {
    if (send_cmd(CMD0, 0) == 1)


    if (cmd != CMD12) {
    if (!select_sd()) return 0xFF;

    both SDIO and SPI NOT working properly.

  • dev_sam

    Both SDIO and SPI not working . In SDIO, File is not created. in SPI sd card mount return FR_NOT READY.

    In SDIO Dma transfer , stucks into while loop till timeout.
    In SPI FR_NOT READ IS retruned freom sen_command function.

    • Point is that library works. So its up to you first, to make sure you have connect it OK first.
      Try with another card.

      • dev_sam

        Thanks for the reply. But I have STM32F4 base board with SD connector, Ethernet and RS232. So, I dont think wiring is an issue, because there are not any wires.

        I have used different cards, Sandisk Micro SDHC 8GB and another local Micro SDHC with 4GB. But still nothing.

        It waits at the while loop, you can see in image attached.

        • Sounds like you disabled interrupts, DMA clock or card is not working. First 2 options are “must check” before continue.

          • dev_sam

            Thanks. But I would like to share my response. I created a file in SD card from my PC with the same name as in code. If I run code then the string is written through the code. Just File has not been created.
            so, I think card is ok. right???

            About Interrupt the following functions are there, interrupts are enabled in those

          • dev_sam

            I am using CooCox ide 1.7.8 .

          • dev_sam

            “FREE_BUF();” inside f_open(); , now hard fault is gone . But stucks at green light only at the end. Because it is still waiting for DMA while loop in screen shot attached above.

          • dev_sam

            made FatFs; fil; global. now everything works fine. Thanks.
            I just wanted to know if we are able to format sd card from code if needed at run time.

          • If not enough stack reserved, it can fail since FIL takes about 550Bytes.

            If there is API function for that, then yes. Probably it is. Check FATFS website for more informations.

          • dev_sam

            I did try f_mkfs. But it going into loop. Not working. Do you know anything else ?

          • dev_sam

            I tried f_mkfs. It returned FR_OK, which means successful. but when I put the SD card (16GB ) into windows PC it asks for format. The format is not recognized by windows PC. Could you please tell me , what am I missing ?

          • Fatfs related, second time. Check there what f mkfs does and what does not.

  • Abhinav Kumar

    Hello Majerle,

    i have a requirement to connect STM32f4 with an external 8mb NOR flash using SPI and when i connect the discovery board OTG pin to a PC, the PC has to display this NOR flash as a mass storage device.

    Is it possible to display the NOR flash as a mass storage device in PC through STM32f4 discovery board.Can i flash the NOR Flash to FatFs ?

    • Yes, you can.

      Check my HAL lib for USB and MSC device example, which is written for SDCARD.
      You must change low-level drivers for FLASH and will work.

  • Bartosz Kościug

    Why didn’t you mention that we should include also the cssbcs file?

    • Because we dont need.

      • Bartosz Kościug

        In the unicode file there is a If statement which demanding cssbcs file… and my programming environment screaming at that line

        • If you didn’t change anything, it should work.

          • Bartosz Kościug

            This happening when I dont change anything

          • Ka Vui

            same for me

          • Bartosz Kościug

            May you tell me, if I correctly included files? Please, look below on the screenshot.

  • Abhinav Kumar

    Hello Majerle,

    Thanks for constantly helping me these days.

    Do you have an example where you interface an external NOR flash to STM32F4 discovery board using SPI communication…

  • Miguel Angel Perez Muñoz

    Hi Majerle,

    I try to use your library with example 21FAT-FS-READBENCHMARK but gives me error 17 (can not write to SD). I tried with two sdcards, one format as FAT32 and other with FAT16. Only changed value is USART (from 6 to 3), but nothing. I tried with PB6 adn PB7 pines to ground (because I read that could be write protected enable) but still nothing.
    My board is Core4x9, is like discoveryF429 (HSE clock is 8Mhz). SD card is configured as SDIO 4bits and wires as as short as I can (about 5 cm). Checked with oscilloscope give a clk freq about 430KHz (I suppose is correct but not completely sure).

    Hope you can point me to right direction because I run out of ideas.

    Hope to heard from you.


    • Why dont you first check what error 17means on fatfspage? Increase heap memory in your ide.

      • Miguel Angel Perez Muñoz

        I searched for fatfs error 17 but can not find anything usefull, found the error page but without any number associated. I understood that I must to count every error…
        Changed to 2000 (instead of 200) and code runs but wroten bites are 0. Modified f_write to fres = f_write(&fil, SD_Buffer, sizeof(SD_Buffer), &cnt); gave me 1 output (FR_DISK_ERR). I´ll try shielded wires and other SDCard reader.

        Thanks for your help.

        • If you didn’t find answer for error 17 in list of errors, then you are nothing else but lazy, sorry.
          Please check FATFS first, when you know what your error is exactly ask here how to solve it.

          But error 17 has been returned by many users so far and fix is already posted here.
          You can also open ff.h file and find error 17 in a enumeration for FRESULT.

          if you don’t know how values are set in enumeration in C, please learn C first before you use FATFS.

  • Gaurav Shekhar

    Hello Majerle,

    Thanks for your library. I am able to create, open, read and close any file easily. But, while writing something on a file, I am unable to write if the file is newly created or it’s an empty file.
    One strange behavior I observed is that if from my Windows explorer I write something on that file and again try writing through software, I am able to write/overwrite only the number of bytes I wrote from explorer. It means it is only able to overwrite something already written.
    Please help me in solving this issue.

    My use case:
    Interface – SPI
    MCU – MB9BF568NBGL from Spansion (Cortex-M4)
    IDE – CooCox CoIDE

    Thanks in advance,
    Gaurav Shekhar.

    • I never had similar problems like you said right now.

      You can, however, first check my and your code for diskio layer.
      Except SPI commands for different MCU’s, you should have similar disk_write, disk_read and others function structures.

      • Gaurav Shekhar

        Yes, my diskio and yours are all the same. I just ported my SPI libraries in your HAL level file ‘fatfs_sd.c’.
        Do I need to check some of the flag permissions while creating a file?

        • Hm.

          no, you don’t need to. Try asking on FF forum.

  • Abhinav Kumar

    Hello Majerle,

    Can you please suggest how do we interface an external NOR Flash to STM32f4 using SPI.

    Do you have a sample code for the same…

  • dou

    i download the project as it is,i want to interface SD card via SDIO protocol, i didn’t change any thing in the project, there no errors but there is no result

    i need help

    • What about pinout, card format and so on.

      • dou

        i want to add rtc librairy to my project but it shows a lot of errors like that

        what should i do ?


        • Check rtc lib!

          • dou

            i download your rtc librairy i added to my project in order to have current date and hour when i creat my files but it shows all time those errors.
            any suggestions!!

          • What about “please” and some other words? 😉

            Like I said. Check RTC lib in details what it requires to get to work. This library has nothing to do with FATFS!

          • dou

            hello, ok thanks a lot 🙂
            i want to use RTC lib in order just to get the right time when i creat my files.
            what should i do?

            thanks for your quick answers. 🙂

          • First check how FATFS accepts time using get_fattime function and then check my RTC lib (for HAL or STD) to use it with this function.

    • dou

      i want to add rtc librairy to my project but it shows a lot of errors like that

      what should i do ?

  • Tom Erbe

    I’m using your FatFS implementation successfully. I am having one problem though. I need to detect whether the card is in the slot or not, and the connector I need to use has no card detect slot. I have tried to use various commands (TM_FATFS_DriveSize, f_getlabel) after the card has been mounted, and then removed, but they usually act as if the card is still mounted. Is there any better way of detecting card presence?


    • Moint again.

      • Tom Erbe

        f_mount wasn’t the right thing to check if the card is still plugged in while the card is mounted. i found a solution – if my program thinks the card is mounted, i just do to f_lseeks – one to the beginning and one to the end of an open file. if it fails i know that the user has pulled the card out. i close the open file and unmount the card. then i require to press a button after putting the card back in. if i try f_mount repeatedly for an automatic mount, it fails when card is being inserted.

  • Harshit Kumar

    I am trying to implement SDIO interface (4 bit).I have disabled card protect and write protect. My SD card is 2 GB in FAT16 format. Only RED LED is lighting up and not green one. This should imply that card is being detected but the file is not opened. Please, help me debug this problem. Thanks.

    • Each fatfs related function has return status.

      • Harshit Kumar

        Can you please elaborate?

        • What elaboration you need? Like I said, each fatfs related api function returns status. You can check for return status and read on fatfs website what this means.

          • Harshit Kumar

            I checked the return status.
            static int get_ldnumber ( /* Returns logical drive number (-1:invalid drive) */

            const TCHAR** path /* Pointer to pointer to the path name */


            This function is returning -1 (invalid drive). Can you please suggest any reasons for my drive being invalid. Thank You.

          • No, you check the status of f_open function. What FR_x is returned?
            Try with “SD:” as path, so file path is: “SD:1stfile.txt”

          • Harshit Kumar

            FR_NOT_ENOUGH_CORE, /* (17) LFN working buffer could not be allocated */

            This is the status being returned. Please explain.

          • Harshit Kumar

            We have disabled the lfn feature (#define _USE_LFN 0) and it seems to be working fine. Can there be any negative consequences of this? Also what do you mean by not thread safe in static buffer mode? Which of these 2 modes should we opt for? Thank you so much for addressing our issues

          • If you have 5 threads and each thread tries to open a file at the same time, so first thread starts, scheduler breaks execution at middle of opening file and starts with another thread again. First you wanna open “file.txt” and this is stored to static buffer. Then, another thread tries to open “file2.txt” and this gets overwritten to first thread because static variable has the same memory location in RAM. Hope you understand.

            Stack or malloc (I prefer) is thread safe.

            _USE_LFN = 0 does not allow file to be greater than 8.3 format (8 chars for filename and 3 for suffix).

  • Mat

    Hi Majerle,
    I have error:

    ..TMtm_stm32f4_spi.c(507): error: #20: identifier “GPIO_AF_SPI4” is undefined

    What I have to do ?
    Can You help me ?

    • You have to stop using Coocox, or at least, update/overwrite STD drivers with latest from website.

      • Mat

        I did like You sad but know I how another error:

        .binbin.axf: error: L6050U: The code size of this image (50572 bytes) exceeds the maximum allowed for this version of the linker.

        • You need license for Keil to use more than 32kB code size.

          • Mat

            I have licensed Keil from University :), I found some answers from the site

            Thanks anyway because I’m making a big project and Im using your libraries which are great !

          • If you would have, there won’t be an error 😀

          • Mat

            Now I have only red diode how can I disable
            Write protect pin. ?

          • Mat

            This is my define.h

            #define FATFS_USE_SDIO 0

            #define FATFS_SPI SPI1

            #define FATFS_SPI_PINSPACK TM_SPI_PinsPack_1

            #define FATFS_CS_PORT GPIOB

            #define FATFS_CS_PIN GPIO_Pin_5

          • All that and even more is described when actually reading post. By the way, check for fres status on fopen and find in comments problem with solution. I know what your problem here is.

  • Mat

    I had only red when I put :
    _USE_LFN = 0 in my defines.h, it works 🙂

  • HB

    Hi, I am trying to make it work on my Nucleo-F411 and have problems with including libraries. I guess i just missed something because i get this error code when compiling:

    Could you tell me what am i missing ?

  • Wuzhou

    Hi, Majerle, thanks a lot for the library. It is very helpful. I got everything working following this post but the writting speed seems to be limited to around 250 kHz for 16-bit data. The writting speed did not change much whether I used SPI, SDIO-1bit or SDIO-4bit. Is there a setting somewhere that I can change to increase the writing speed? I want to write the data at more than 1 MHz. Thanks for your help.

    • For start set pll for max clock. Second, what is 250khz? This is not datarate.

      • Wuzhou

        Yes. I have set the PLL for max clock based on the instructions from Library 3. Regarding the writting speed, the command “f_write(&fil, &WriteBuff, 2000, &ByteWrite); ” takes about 4ms, which is equivalent to one 16-bit interger for 4us and thus the writting speed of 250 kHz. Thanks for responding so quickly.

        • It is obvious you didnt even search first before asking about fatfs best throughput. And write speed is not measured in kHz but kB/s.

          • Wuzhou

            I did google it but could not find much useful information about the maximum write speed. Do you mind posting the link? In kB/s, the maximum write speed I got is 500 kB/s.

  • Harshit Kumar

    Hello Tilen,
    I’ve been trying to write the data from MPU6050 onto my sd card. I’ve been monitoring this via usart. At first it is writing fine but it stops randomly. On hiiting the reset it again starts, but after some random time it stops again .

    Here is my code:

    Please help. Thank you.

    • For start, use fatfs related functions global.

      • Harshit Kumar

        Please elaborate.

  • Mert Mutlu

    Hi Majerke, i guess u r fine.
    My problem is “diskio.h”, “tm_stm32f4_sdram.h” , #include “ff.h” , #include “usbh_usr.h” errors. Error is cannot open the source file, no such file directory. I did everything u already wrote, i added libraries firstly “add extising file to group user” and then i did in “options for target” >> “C/C++” >> “include paths” and i include all these files you wrote. I dont know why keil sends me error. I have forgot anything about including library ? I know i have basic logic error.

    Best Regards
    Mert Mutlu – TURKEY

    • You forgot all paths. That’s clearly visible or you actually don’t have those files.

      • Mert Mutlu

        But i see on left side, i added all paths u wrote. Isn’t it ? How it can be possible

        • You screens don’t have any valuable informations here. You simply didn’t include all paths or you did not have .h files. Simple as that.

          • Mert Mutlu

            Okay, thanks

  • محــمد مهــدی سلطانی

    How to Delete a file?

    • FATFS API documentation is your friend.
      Btw, f_unlink exists.

      • محــمد مهــدی سلطانی

        oops, I made a mistake…
        I mean to delete some characters inside a file…

        I didn’t find any thing about that inside the FATFS API documentation…

        do you know how to do that?

        • Fatfs api is not something windows or others can do in general.
          You have to detect position of characters you want to remove (first character to remove) and then shift (copy) content from below removed characters back up. After entire process, truncate remaining chars from file.

          Not straightforward but can be done pretty easily but (!!) very unefficiently.

          • محــمد مهــدی سلطانی


            that is so bad for a file that is big as 2 MB…

          • True.

  • Алексей Кудрявцев

    Hi Majerle,

    I have 2 problems:

    Error[Pe167]: argument of type “void *” is incompatible with parameter of type “BYTE *” C:Projectsex1APPLICATIONFatFsfatfsdriversfatfs_sd_sdio.c 352

    Error[Pe167]: argument of type “void *” is incompatible with parameter of type “BYTE const *” C:Projectsex1APPLICATIONFatFsfatfsdriversfatfs_sd_sdio.c 402

    Can You help me ?

  • 詹曜寧

    Hi Majerle,
    Thanks for your library. I have a problem between “f_mount” and “f_open” in main.c. I load the code into STM32F4DISCOVERY and there is no led was on, and I followed your suggestion check the SD card format is Fat16 first, then I was added an infinite loop after TM_DISCO_LedOn(LED_RED), and red led was on. So I am confounded the bug is in “f_mount” or the next function “f_open”. Could you give me some suggestion? Thank you lot.

    • You founded a bug? Wow that must be very hard to prove.
      You have debug option I would say and go and check return values for f_mount and f_open.

      I think you have HEAP problems. Increase it.

      • 詹曜寧

        Thanks for your reply. I was executed “f_mount” it returns 0x01(FR_DISK_ERR), then I was executed “f_open” it returns 0x0C(FR_NOT_ENABLED), that’s weird I got “FR_DISK_ERR” but red led still turn on.

        • Go to check FATFS API what means FR_DISK_ERR. You have problems (in most cases) with pin configuration for your card. Do you use SPI SDCARD connector with SDIO mode? This won’t work.

          • 詹曜寧

            I didn’t know the connector have SPI or SDIO mode, so I am going to check (1) connector layout, and (2) what means FR_DISK_ERR. I need some time. Thanks again.

          • 詹曜寧

            Hi Majerle,
            I already check the connector datasheet, this connector can support both SDIO&SPI. I also check the FR_DISK_ERR using debug mode step by step, and didn’t get error return by “f_mount”. Finally, I think this bug is caused by compiler, because I notice the code size is wrong. Before I added an infinite loop, the code size is about 12kB(“f_mount” return FR_DISK_ERR ). After I added an infinite loop, the code size is about 7kB(“f_mount” return FR_OK ). Maybe is memory address issue. Do you have any idea?

          • 詹曜寧

            Hi Majerle,
            I fixed this issue by modify the stack and heap size in startup.s file. Now the program is work. Thanks for your library.

          • David Nguyen

            How did you do ? me neither, code’s does open fille and red led still on!!!

  • DannyM

    Hey Tilen

    I’m new to coding and managed to successfully write to a SD card using your library. I’m using the STM32F429i board and would like to store to a SD card multiple times but have not been successful with this. Any help would be appreciated.

    • What help you need?

      • DannyM

        I would like to store multiple entries below each other in CSV format but the code only stores to one location. Which variables do I increment to prevent it from overwriting my data.

  • Ka Vui

    I met a problem during compiling as shown in pic. Any1 can help?

  • Ka Vui

    Hello there, I met a problem while using this libraries in coocox which as shown in the picture, any1 able to solve that? that problem is come from ccsbcs.c

  • Ka Vui

    Do we need to include ccsbcs.c? since unicode.c need it

  • Ka Vui

    I have a question, why you dont need to initialize the GPIO port for the SDIO? U able to use the FatFS directly without initialize hardware??

    • What? I do initialize everything!

      • Ka Vui

        Hmm I saw it sry. Because the problem i met is after i mount the sd card then whole program hang, I dont know whats behind haha

  • Thuk

    Hi Majerle,

    I am trying to read data from IMU ADIS 16480 through SPI (SPI mode 3 and data size = 16b) and save it to a text file in sd card. I created 2 projects. One to read data from IMU, another to test sd card using your example. The two projects worked just fine individually. However, after I combined them, I was able to write data to sd card, but cannot read from the IMU.

    Is there any thing that I forgot in configuration?

    Thank you!

    • Thuk

      The IMU responds OK but cannot get the data. please help!

      • How is this related with SDCARD library?

        • Thuk

          Hi Majerle,
          When I use SDCARD library, I can’t get data from IMU. As you can see above, IMU still outputs data on MISO pin, but somehow stm32f407igt6 read it as 0x00

          • Still not related to SDCARD library.

            Nice. How your wiring looks like for both devices?

          • Thuk

            I use SDIO for sd card and SPI (SPI1. pinpack1) for IMU. The problem is when I read IMU without sd card library, it works fine. Data lost when sd card is declared in my code. I’m thinking there are some conflicts here, it may related to DMA (not sure).

          • I did not receive informations I asked from you.
            And still, not related to SDCARD problem. Another thing, if you are using SPI with DMA, then I assume you know what you are doing 😉

            So ask specific question, not “it does not work, help.” because I won’t answer.

          • Thuk

            I am not using SPI with DMA but I saw it somewhere in your library so I just guessed. I just want to know if there were some conflicts between SPI library and sd card library if they are used in the same project.

            Thanks for you time!

          • No conflicts. End of story here.

          • dasrotemopped

            Hi TM,
            I am experiencing some similar Problems using SPI and SDIO (Nucleo-F401RE) or SPI and SDMMC1 (Nucleo-F746ZG) at the same time. Initialising the SDcard Interface makes the SPI stop working completely. Did you successfully test a ili9341 display with an SDcard for example ? If you confirm please that your 2 libs work together, I perhaps have a Chance to fix my Project when i can spot the difference between your libs and my CubeMX libs. Best regards, dasrotemopped.

          • It worked for me.

          • Check HAL version. This lib is not for hal. I have another.

          • I can clearly say that this lib works perfectly. If you use CubeMX, then you don’t need this lib because CubeMX generates this for you.

  • Mert

    Hi Majerle;
    I want to read and write to SD card in 4bits SDIO via micro USB. Between computer and my device. Last version in my project i did flash drive but sd card is more acceptable for me. Can i do that with u r libraries. Best Regards.

  • Jack


    “rn” does not work for many writes and overwrites data when used as a data logger.

    • I absolutelly don’t believe you.

      • Jack

        I’ve stepped through the code numerous times using different sd cards and the program constantly writes to the first location.

        • First of all, im not author of fatfs lib and second, show code.

          • Jack

            Sd_card represents the function defined similar to yours but constantly writes to the first line of the sd card.

      • Jack

        I’m calling the function every second to record values from my ADC

        • Before you hate my work, check fatfs api on official web and what it does and how go to the end of file before writing new data!!!

  • David Nguyen

    Hi Majerle,
    I also carefully did like your post. But the issues is ONLY RED LED ON!!!
    In define.h, i defined to use SPI1 – Pinstrack1 on STM32F407VG Discovery board. I really don’t know why code’s doesn’t work.

    Would you like give me some advise?
    Thanks and best regards!

  • Jarno Tuominen

    Cheers Majerle – nice work!

    I would like to check something related to SDCard initialization in SPI mode.

    The SDCard specs say: “The host shall supply power to the card so that the voltage is reached to VDD min within 250ms and start to supply at least 74 SD clocks to the SD card with keeping CMD line to high. In case of SPI mode, CS shall be held to high during 74 clock cycles.” Also, the clock frequency should be 100-400kHz during the initialization.

    I’m looking at your TM_FATFS_SD_disk_initialize() -function, and notice that you are calling TM_SPI_Send 10 times – which for sure generates the required 74 clock cycles. However, I wonder where do you control the CS-signal during these 10 bytes… or is it toggling normally for each byte transfer? Furthermore, where do you configure the clock frequency of the SPI interface (before and after disk init), as I suppose that you are ultimately running the SPI I/F at much higher clock freq to get reasonable data rates.

    With best regards,

    • I dont care regarding spi so much because stm has sdio for this purpose. However spi is here only for presentation that it works.

      • Jarno Tuominen

        Ok 🙂

        The reason why I was asking this, is that I am working on some other platform (having Cortex-M0, no DMA, no SDIO .. Uhh.. ), and I’m facing some pretty nasty random-like errors when initializing SDcard – some cards work – some don’t – depending on the card manufacturer, the number of sun spots and the ratio between EUR and USD currencies… and of course my shoe number!

        So, I’m pretty much challenging every line of my code. Currently I’m shutting down the “SPI engine”, detaching it from the I/O-pin, then bit-banging-the clock pulses and so on… I thought that you have seen some issues with the initialization as it is not according to spec.

        Anyways, keep up the good work! My next project will be probably 32F7-based, some of your libraries might be soon ported to that platform as well – I will keep you updated when that happens 🙂


        • I never faced this, even with at least 10 cards with SPI of different brands. I’m not so sure this is a problem, but it could be.

          • Jarno Tuominen

            This is most likely related to SPI timing issues – the bus itself works just fine – I got several sensors connected to it with no problem, but I had to write the lowest level of SPI driver in assembly to squeeze it to maximum speed. The SDCard full spec is unfortunately not free of charge, whereas the free, simplified specification does not include SPI timing diagrams.

          • Just for the can’t do it faster in assembly than with hardware SPI.

          • Jarno Tuominen

            Not at the physical HW level, but as I mentioned, there is no DMA, which means that the CPU needs to transfer data from my SPI rx/tx-buffer to 2-bytes deep buffer of the SPI HW engine. Running SPI @ 8MHz (1MHz byte rate). While my CPU clock is 16MHz, that does not leave very much room for extra opcodes in the inner loops. ARM compiler sometimes produces shitty code, even with highest optimization levels.

            Most of these can be handled by coding C very carefully (and keeping the disassembly window open!), but not all. For example, if you try to “optimize” your memory usage by introducing uint8_t type loop counter, you’ll notice that there will be extra opcode for doing byte to word extensions (UXTB Rd, Rm). Similarly, if you have struct representing your SPI HW instance (with txbuff, rxbuff, bytecounters etc), you should make a local copy of all those pointers to avoid indirect register accesses (e.g. LDR Rd, [Rn, #] ), which takes 2 clock cycles each. Direct access (MOVS Rd, Rm) takes only 1 cycle.

            A real life example what C compiler did:

            MOVS r6,#0x00
            MOVS r7,#0x00
            LDRSH r6,[r3,r6]
            LDRSH r7,[r2,r7]

            And what I did:

            MOVS r7,#0x00
            LDRSH r6,[r3,r7]
            LDRSH r7,[r2,r7]

            See the difference 😉 I found no way to fix this in C. Sometimes it’s just so much easier to make it right in asm rather than trying to code C so that the compiler figures out what you mean.


          • It’s time to move to STM 🙂

          • Jarno Tuominen

            Haha 🙂 I used to work for STM (ASIC design + embedded SW). I’ll finish my PhD first, then I might move to STM 😉

  • Gergely

    Hello Majerle,

    Thanks for the lib. I have a problem for what I didn’t find solution in the discussions.
    SDIO works for me but only with some SD cards. It’s not even a file system but low level stuff.
    TM_FATFS_SD_SDIO_disk_read fills the buffer with correct data on some SD cards and fills random data into the buffer with some other SD cards. It’s independent of the class, size and type of the SD card (SD, SDHC). Every SD card workis with SPI, but I would like to use SDIO.
    Do you have a suggestion what could be in the background?
    (Data and command pins are pulled up to VCC with 47k resistors)
    Thanks in advance.

    • This is sometihng strange even to ask. It can’t be possible that sometimes work with other card and sometimes it doesn’t. Or it works always or never I would say.

      What exactly are those “random” data? Are those “random” data always the same random?

      • Gergely

        It looks like now that it inserts extra 4 bits in the data and the following data is all shifted. This seemed to me as random data at first.
        I have written 1-255 values to the first sector with TM_FATFS_SD_SDIO_disk_write I checked the result with HxD hex editor program that can show me the binary content of the SD card on Windows.
        Then I read back the data with TM_FATFS_SD_SDIO_disk_read and find that starting after 0x0E everything is shifted with 4 bits. I circled the extra 0 in the image. What do you think? Thanks for the fast answer 🙂

        • Gergely

          It seems to happen again at the line starting at 0x2000248E before F2 fixing the rest of the data but causing a full extra byte in the data

          • Gergely

            So it actually misses that lower half byte from 0x0F and later the upper half byte of 0xEF. It always happens at the same place and with about half of the SD cards that works otherwise properly with SPI.

  • Fons_mol

    When trying to open a file via the SDIO interface, I received a hardfault. Mounting did work. I solved this problem by replacing:
    FIL fil;
    by a static variable:
    static FIL fil;

    In the main(void) function in the example given above, might help others with the same problem!

    • A proper way to solve this problem is to increase stack size because you come to stack overflow.
      Another way is to use global variable (as is the same as static in side function) but rather use global for this purpose.

  • Jean Paul

    Hi, I am trying to include your library into my workspace using System Workbench for STM32. Using the STM32F4 Cube Discovery template, there are some redefinitions from the HAL header files. Any suggestions to integrate it without too much trouble?

  • Pradeep Chl

    Hi TM,

    My question is FATFS specific.

    For f_write() function, we need to use f_sync() following f_write() to move the data from cache to the file..

    Likewise, do we need to use f_sync() or any other function when calling f_gets(). ?
    Looks like, I am unable to read the data from a binary file properly using f_gets().


    • Yoi dont need. Pretty logical. F gets reads one line, so it waits for crlf or lf only char. In binary file, you need f_read.

      • Pradeep Chl

        Thanks TM, it was helpful.

        Can we write to a created ogg file using f_putc()…
        I have data available in a register.. when I am writing available word to the ogg file using f_putc() character by character, it seem to write slower..I use f_sync() as well..
        I use ogg format to record the data from VS1053 audio codec..

        The data being written to file seem slower than the available data I have from VS1053..


        • Before asking me a FATFS related questions, search on Google.
          f_putc writes only one character meaning it has to read sector, change that one character and write sector back. This takes time…use f_write instead with 512 bytes writes or more.

  • Alirio Filho

    Hello Majerle,

    I come again ask your help to make sd card work with stm32f417 from PowerMCU.
    I tried SPI and SDIO 4 and with 1bits but always returns the error FR_NOT_READY.
    In the arduino with shield the sd works, this one with FAT32, but already I tried with FAT16.
    Any tips that might help?
    Thank you!

  • Lingaraj Panneer Selvan

    Hello Majerle,

    I’m a fan of your tm_ driver codes. I have interfaced FatFs with SDIO properly & it’s working.Now, I would like to work on FatFs – SPI. I have included necessary files in the build. I’m struck on where i have to start in the main function. I have started with TM_FATFS_SD_disk_initialize();. So, could you share any example main code snippet with FatFs-SPI.

    • If you look at SDIO example, do you see anwhere TM_FATFS_SDIO_disk_initialize call? No, you don’t.
      I would say I described SPI pretty good which define is necessary to set and value to set it.

      Anyway, I have a question..why would you want SPI instead of faster SDIO?

      • Lingaraj Panneer Selvan

        Due to pin constraint. I’ve used SDIO Pinspack to other interfaces.@majerletilen:disqus

        So, I can use the following Psuedo code directly without calling TM_FATFS_SDIO_disk_initialize ?

        mount the disk
        //writing something
        unmount the disk

        • SPI init is called from f_mount.

          • Lingaraj Panneer Selvan

            Hi Majerle,

            you are right. TM_FATFS_SD_disk_initialize which is called from f_mount. But, code returns after trying to put SD card idle in TM_FATFS_SD_disk_initialize. I’m getting reply of 0xFF in

            if (send_cmd(CMD0, 0) == 1) { /* Put the card SPI/Idle state */

            what maybe the reason for this return. Pulled up resistor used is 10K for SCK,SS, MOSI & MISO, measured input voltage for SD is 2.96V.

  • Pedro


    I trying STM32F4 Discovery board + SDIO + FATFS and i get the erro:

    SD_PowerON OK
    SD_InitializeCards OK
    SD_GetCardInfo OK
    SD_SelectDeselect OK
    SD_EnableWideBusOperation OK
    mount device NOT OK

    Could you tell me what am i missing ?

    • Crc failed as you can see. Too long wires?

      • Pedro

        the size of the wires is approximately 7 cm ~ 2.76 inches
        I’ll try to reduce the size
        it is necessary Pull-up resistors like SPI?

        • Pedro

          ok, found the problem, it is necessary put pull-ups.

    • Pedro

      when i do
      f_mount(&FatFs, “”, 1); the return is FR_DISK_ERR

      • You already know the problem. Crc fails. You did not answer my question.

  • Mustafa

    Hello Majerle,

    I created .pdf file with your file system code but when i open with computer it did not open.
    Acrobat redaer said “This file system does not support.”
    But when i open .txt there is no problem. Everything is ok.

    Piece of code,
    if (f_open(&fil, “STM32F429_Log.pdf”, FA_OPEN_ALWAYS | FA_READ | FA_WRITE) == FR_OK)

    What do you think about this subject.

    Thank you.

    • The most funny comment ever 🙂 it is not fatfs probpem or my lib. Pdf file is not just plain file like txt. Open your pdf with notepad for test.

      • Mustafa

        I think your answer is very funny.
        I think You misunderstood my question. I dont want to find any problem on your code or fatfs.
        Only want to solve this problem.

        I can open .pdf file with notepad++, but how can i open directly acrobat reader.
        Last day I saw a device, there is a pic16fxx. When i pou on pc there is a .pdf and directly open acrobat reader.

        I hope understand 🙂

        • You have to create binary file for pdf structure. Not that easy.
          Open one working pdf with notepad and you will see what is there

          • Mustafa

            Ok. Thank you. I need this answer.

  • Xavier P.

    Hello Majerle !
    First af all a very big thanks for your work, It is encouraging for all developers especially on stm32f4xx ^^
    I have try to integrate your library with fatfs in my stm32 kernel, not so complicated 😉
    When I use function : TM_FATFS_SD_SDIO_disk_initialize(); the result is OK : so I can see my sd card, with some basic information like capacity or size_blocks.
    When I try a f_mount or most basicly a SD_ReadMultiBlocks(…); the result is that I’m still blocked in the SD_WaitReadOperation (); and the flag SDIO_FLAG_RXACT nevers comes. In addition I can see I receive a RX_OVERRUN result in SDIO interrupt.
    I’m using DMA / I’ve check all clock (F_SYSCLK = 168Mhz / HSE=8MHz / APB1 = 42Mhz / APB2 : 84Mhz )
    On SDIO startup I can see the command line, and some frame passing on Data Line but never when I try a read_blocks.
    I’m using a stm32f405rgt and gcc compiler.
    I do not know what to look at, does it speak to you ?

    • Im aware of that. This happens when rtos is used because of disabling and enabling irqs. Entire dma would solve problems.

      Download cubef4 and check bsp file for f469 disco for example for sdcard. There is dma read blocks example.

      • Xavier P.

        Ok, I did not specify : i do not use HAL driver but std librairy, Is your answer the same ?

        • Still. Reference code.

          • Xavier P.

            i’m watching the code, there is some difference, especially the use of 2 different channels in DMA for Tx and Rx and their initialization at startup and only here 🙂 hopes this code will help me…

          • Xavier.P

            I’have DL and read the BSP file in the f469 example, not so simple… and I succeeded to trigger DMA IT , but (there’s a but) I still have RX overrun problem.
            So I did a test by disabling the DMA mode and using polling mode and I could see that I always had a problem: data timeout….
            It is as if the SD was well initialized but the SDIO receives nothing when the “read command” goes, because I always have the basic info after init_SD().

          • Xavier.P

            Hello Majerle, all is working now ! The last problem
            I had was due to the fact that my RAM area is declared in CCM and not
            into SRAM1 or 2 which are the mandatory with DMA2 (because it’s impossible for DMA2 to read/write into CCM). Nice to use your library, thanks for the help 🙂

          • Erwan Dureau

            Hello Xavier,
            I have the same problem as you describe and I’m wondering how did you manage this issue ? First, Did you initialize the DMA Tx and Rx channel as in the bsp file for f469disco ? i’m a little lost in that example…

  • mert

    Hi Majerle,
    Thank you for good application. I need your help.

    I’m having trouble with codes. I use stm32f429 discovery kit and keil u vision5.
    This code is working:
    if(f_mount(&FatFs, “0:”, 1) == FR_OK)
    But this code is not working and when I debug, I see that there is an infinite loop here:
    if (f_open(&fil, “MERT.txt”, FA_CREATE_ALWAYS | FA_READ | FA_WRITE) == FR_OK)
    I’ll be glad, if you help me.Thank you

    • If you know that it is infinite loop, then you also know which one is.

      I can only guess. Make fil and fs variables global instead local.

      • mert

        I don’t know.

        The txt file is not being read or opened in the sd card.

        • Find out what is return value from f_open function. You can use debugger to debug the code and when “infinite loop” happens you can stop debugging and you will know where you are.

          Btw..are you sure it is infinite loop? Or is just “it does not work” and it might be infinite loop?

          • mert

            When I delete ff_memalloc() function in syscall.h, Program is run and it made file in sdcard.But this file hasn’t .txt extension. it name is 䝰 not mert.txt. it hasn’t any extension and empty.

            What is the reason? I use 4 bit sdio communication. How to do spi adjustment for spi communication?

          • This is clear as ff_memalloc() is used for long file names. This means that you did NOT disable long file names as I suggested yesteerday. If you would, ff_memalloc() wouldn’t be called at all and you would not have these problems.

            Regarding SPI, everything is described in post above. I don’t know if you had even check post before commenting.

            You can show ffconf.h file by using external website. But I can guarantee you long file names support is set to 3 which means that either you ignored my adviced or you just modified something else (without even reading why configuration is used).

          • Arnold

            I went crazy while reading…You didnt even done what Majerle suggested and give very less information and hoping for help?! Majerle has some patience…

      • mert

        I make global variables but not working

        • I would need more cooperation from you. “Not working” is not enough for me. I believe you have problems with HEAP memory.
          Go to ffconf.h file and disable long file names. Set it to 0.

          Please don’t ignore my advice about debugging and getting return value from f_open function. I can’t help otherwise.
          Let’s speak in clean English, please.

          • mert

            I debugged. Infinite loop code is here in syscall.c file:
            void* ff_memalloc ( /* Returns pointer to the allocated memory block */
            UINT msize /* Number of bytes to allocate */
            return malloc(msize); /* Allocate a new memory block with POSIX API */

            The code is return infinite loop>> return malloc(msize);

          • mert

            The program is not progressing from this code and debug process is locked or infinite looping.Debug/com led is constantly green and red on stm32f429 discovery kit.

          • I don’t want to talk things twice. Before i said: “Go to ffconf.h file and disable long file names. Set it to 0.”

          • mert

            I did but it doesnt work yet

          • Ok. So I assume now f_open returns some value. Get this value and report it here. Furthermore, you can go to FATFS official website and check return value meaning yourself. If you really set long file name support to 0, then there should be no infinite loop in ff_malloc function as before. If it still is, you failed.

  • vm

    Hello sir,
    Your Fatfs library doesn’t have open/write file in append mode feature.
    how to implement that in this code sir ?

    • After you open file, call f lseek with size of file.

  • vm

    Hello sir,
    when i try to open file using f_open() returns error as 0x11 i.e. FR_NOT_ENOUGH_CORE
    what this actually mean and how to solve this.
    my sd card is empty fully and has capacity of 8GB.

  • vm

    Hello sir,
    i am trying to store object to a structure in a file on sd card using f_write() but values are not correctly written. can you tell me how to do that or how to write object to a structure in a file on sd card ??

    • Using f_write. I dont know what does it mean dont work.

      • vm

        when i am writing a structure in file , it has 3 members, one char array and two int variables, the char array is written correctly but other two int variable are not showing in file.

      • vm

        when i am writing a structure in file , it has 3 members, one char array and two int variables, the char array is written correctly but other two int variable are not showing in file.

        • I suggest you show the code. I believe they are written just not displayed as they are not visible chars.

          • vm

            why integer variable values are not visible sir ??

          • I still suggest you show the code and lter start good C book. Integer will be visible once you convert it to string.

          • vm

            yes converting them into string is visible.

            thanks sir for your support.

  • vm

    Hello sir,
    all the function in your library are available to write char constant in fatfs file, what if i have to store integer variable values in a file. how to store integer variable values ??

  • Sidharth

    I am a total newbee in STM32. Can I possibly modify your library so that I can use SD card with stm32f0 discovery board?

    • Sidharth

      I am referring to the SPI part of the library as stm32f0 does not have SDO.

  • Harry May

    Majerle, You are my Hero ! Very very well done. I have build your library on an STM32F207 with a 7″ TFT display. This display contains a SD card holder which I connected to SPI1. The SD card worked at the first try without any changes !!! Excellent work.
    Best Regards
    Kurt, Germany

  • Eugene White

    Hello Majerle,
    I am using Coocox’s CoIDE, and I am facing trouble compiling. It’s showing a large number of errors in the “fatfs_sd_sdio” files, basically showing that none of the functions of “stm32f4xx_sdio.h”, “stm32f4xx_dma.h” or “misc.h” are being included, even when they are added to CoIDE. After manually including all of these in the “fatfs_sd_sdio.h”, it shows “collect2.exe: error: ld returned 1 exit status”
    Could you help me out? Do you know what could be the problem?

    • From this info it is not enough to tell you. Try to rebuild to see if any more error messages you receive.

  • Debraj


    I used your SD card SPI driver (with modification to my other code) and it works great. But one point that I notices is that the SPI initialization happens once only (which may be lower speed, as SD card initially needs 100K to 400K). But later, after few steps of initialization, the SPI speeds can be increased to 1MHz or higher (depending on class of SD card). I remember doing it earlier with Microchip PIC drivers. Do you know or aware of where that increase in SPI speed is allowed?

    • By specs, SPI should be like you said when initialization process is active (only on beginning). Later, normally more than 1MHz can be applied easily. This is not done in the lib, but you can easily change this.

  • DavidTeo

    Hi Majerle,

    Thanks for your libs, they are great help to me working on the STM32F4, custom board.
    I am using your SD STM32F4 SPI drivers and FATFS by Chan R0.11 to access SD-card. (SPI-bus due to design constraints), using an rtos.

    I have a query regarding timing observations on deleting files on the SD-card on the above setup.
    1) SD-card with directory [X].
    2) Copied a set of files (say 200 files) into directory [X] via PC and a SD-card reader/writer.
    3) Put SD-card into my STM32F4 device (config as above).
    4) Delete the 200 files via the FATFS and SPI drivers.
    The directory [X] is untouched.
    Assume the timing duration to complete deleting the 200 files observed here is time T4 (say 12 seconds).
    5) Repeat from step (#2) to (#4).
    At (#4), the time observed T5 is now ~ 21 seconds.
    6) Repeat from step (#2) to (#4).
    At (#4), the time observed T6 is now ~ 30 seconds.
    7) It may takes several repeats before the timing went back to time T4.
    8) Also, If i re-perform the 200 delete operations again after step (#4), the files were deleted already, the time T8 in this step will be the same as the time taken in step (#4).
    Ie. if step (#4) time was T4, then T8 is approximately T4.
    Ie. if step (#4) time was T5, then T8 is approximately T5.
    Ie. if step (#4) time was T6, then T8 is approximately T6, etc.

    I am trying to figure out now is where this unexpected increased time might be due from.
    a) rtos (x)
    b) ffs (o)
    c) spi drivers (o)
    d) sd-card (o)

    – (a) rtos is the least likely contributor, which leaves me the rest to contend.
    – Could the SPI drivers (c) be a likely factor?
    – My assumption points to it being the SD-card’s controller behaviour in all likelihood, however, i feel it would be good to get various expertise and views from you and any other readers here as well.

    • Please read application note first on fatfs website about deleting big files (or deleting a lot of files).

  • Peter Mather

    Hi Majerle

    I’ve been using the FATFS code with an SPI interface successfully but want to convert to SDIO and am hitting problems as per the log below. Any ideas where to look would be appreciated

    SD_PowerON OK

    SD_InitializeCards OK

    SD_GetCardInfo OK

    SD_SelectDeselect OK

    SD_EnableWideBusOperation OK




  • Peter Mather

    st432f4-discovery board

    FATFS is working fine with SPI but I’m trying to convert to SDIO. Whether I use 1-bit or 4-bit I’m getting an error “SDIO IRQ : SD_RX_OVERRUN”. Any pointers as to where to look appreciated



    • I suggest you check stn32cubef4 package with examples.

      • Peter Mather

        Looked in there and there is nothing for SDIO at all on the F4-discovery.

        Googling suggests this is an issue without a specific solution and exists on HAL as well as API. May be too long spent in another interrupt? Can I raise the interrupt priority of the SDIO DMA and reduce the priority of systick somehow?

        • Peter, look at F4 EVAL board, F439_EVAL could be the one. Since SDIO is the same in all F4 MCUs, you can reuse from another project.

          • Peter Mather

            Will do, but in the meantime I also tried HAL version and it won’t compile because of changes made in cube 4.20. The thread I reference also suggests there may be an issue with the latest non-HAL api so that may be the problem. I’ll try and use older versions of the library as well

    • Peter Mather

      OK I’ve found the problem. I’ve put the stack and heap into CCMRAM to improve performance but I now learn you can’t DMA into or out of CCMRAM and FATFS in places sends/receives data to/from local function variables that will have been created on the stack by the compiler.

  • We are using this Micron MTFC32GAKAEJP-4M e.MMC in one of our design with STM32F777II mcu, where I wanted to know:

    1. Does STM (may be through cubemx) provides any driver set written already for talking to these JEDEC standard version 5.0 based e.MMC?

    2. Will it work with the Chan’s FATFS middle-ware provided in through CubeMX?

    3. Any ideas if the JEDEC standard version 5.0-compliant e.MMC are backward compatible to older versions of SDCards/MMC?

    • It will work only if you write driver on your own for FAT implementation. for 3, I’m not sure.

  • Ali Tarek

    Hello Majerle,

    i try to use SDIO and FATFS to read and write on SD card using stm32f407 discovery
    i get an error and search a lot but not find the solution .
    when i use f_mount() function it gives me FR_OK and when i use f_open() it gives me FR_DISK_ERR. i check the format of the SD card and every thing .
    fresult1 return ok , but fresult2 return FR_DISK_ERR.


  • Ferhat Yol

    Hello Majerle,

    I downloaded your library and added the my project. But I Have a problem. The library was compiled without problems. I did the SDIO Connections properly. At the same time, I added the definition “#define FATFS_SDIO_4BIT 1” to “defines.h” file

    I compiled a sample program that you shared and I loaded it to the STM32F4 Discovery. The problem now is that f_mount query resulting in consistently negative. I did not understand the problem.

    Then I found another test program that uses SDIO. The new library I found worked without any problems. But the library I found uses the SD Detect pin.
    I did not define the SD Detect pin. Can the problem arise from this? Why does f_mount not work?

  • bcclsn

    I’m trying to use this library but without success 🙁

    – STM32F4-Discovery
    – SPI1
    – TM_SPI_PinsPack_1 (GND, +3v, MISO->PA6, MOSI->PA7, SCK->PA5)
    – GPIOB PB5 for the CS pin
    – 1GB sd_card formatted in FAT16

    I have “no leds on: It has not been mounted ok” but I’m not sure because I can’t debug… weirdly, I can’t add breakpoints in debug mode.

    so, please, can you help me?

  • bcclsn

    hi 🙂

    I’m trying to use the demo but I have a problem with the mount of the sd card. f_mount failed with code error 0x03 FR_NOT_READ. I tried to debug, but I didn’t understand where is the problem.
    I configured defines.h like you said and I increased HEAP and STACK from 0x200/0x400 to 0x2000/0x4000 but without any success.

    thenks in advance

  • Adolfo Sánchez


    I am new to ARM processors, just starting a project and I am learning how to write to SD cards, would this project work with a Cortex-M4 processors? Would require any modification? Or should I search a different library?

    Thanks for your help.