This project is designed as an example of a STM32CubeIDE-generated system with FatFs middleware controlling an SPI-connected MMC/SD memory card.
The project was initially created in CubeIDE, and then code written by ChaN was ported to fit the CubeIDE generator.
This is a remake of the original project provided here for CubeIDE instead of CubeMX.
I also wrote a blog post which accompanies this repository and explains how to use it.
- Copy the driver files
FATFS/Target/user_diskio_spi.c
andFATFS/Target/user_diskio_spi.h
into your CubeIDE project which has been configured to use FatFS. - In
FATFS/Target/user_diskio.c
add#include "user_diskio_spi.h"
- In
FATFS/Target/user_diskio.c
callUSER_SPI_initialize(...)
inUSER_initialize(...)
,USER_SPI_status(...)
inUSER_status(...)
,USER_SPI_read(...)
inUSER_read(...)
,USER_SPI_write(...)
inUSER_write(...)
, andUSER_SPI_ioctl(...)
inUSER_ioctl(...)
.
- We embed in this manner to avoid conflicts with the CubeIDE code generator. Make sure these function calls are inside the
USER
comment blocks.
- In
main.h
ensure that you have#define
s forSD_SPI_HANDLE
(e.g. hspi2),SD_CS_GPIO_Port
, andSD_CS_Pin
. - Double check what would be suitable high/low speeds for your SPI driver and the prescalars you will need to use for the SPI port. Configure these at in
user_diskio_spi.c:
//(Note that the _256 is used as a mask to clear the prescalar bits as it provides binary 111 in the correct position)
#define FCLK_SLOW() { MODIFY_REG(SD_SPI_HANDLE.Instance->CR1, SPI_BAUDRATEPRESCALER_256, SPI_BAUDRATEPRESCALER_128); } /* Set SCLK = slow, approx 280 KBits/s*/
#define FCLK_FAST() { MODIFY_REG(SD_SPI_HANDLE.Instance->CR1, SPI_BAUDRATEPRESCALER_256, SPI_BAUDRATEPRESCALER_8); } /* Set SCLK = fast, approx 4.5 MBits/s */
You can now call the FatFS functions from your main()
. For more detailed explanation of this, with examples, check out the blog post.
Also note that if you're using this process with your own custom circuit, you may need pull-up resistors on the SCK, MISO, and MOSI lines. The SD card module I used in this post includes them internally - if you're wiring your own design, you might find you need to add them. You can also consider enabling the internal pull up resistors. More details are included here.