Skip to main content
Associate
Question

How to communicate STM32F429 discovery with SD card using SPI communication?

I'm working on a project on STM32F429 discovery board, because of the small size of the internal flash I have used SD card module with SPI communication standard to store the images

For the STM32F429 Discovery board, I have developed functional code to read data from an SD card via the SPI4 interface.
The failure encountered while working with the SD card was not due to a single bug, but rather a chain of five architectural and software-related mismatches between FatFs, FreeRTOS, the HAL SPI4 driver, and the hardware
protocol for microSD initialization.

Errors occur consistently during SD card initialization.

14 replies

ST Technical Moderator

Hi ​@AVKrobotics 

Would you include the code or the failing command response. To help us investigate each problem more effectively, please create a separate post for each issue and include the relevant code, error messages and if possible minimum firmware to reproduce the issue. 

To give better visibility on the answered topics, please click on "Best answer" on the reply which solved your issue or answered your question.Best regards,FBL
Andrew Neil
Super User

Welcome to the forum

Please see How to write your question to maximize your chances to find a solution for best results.

 

The failure encountered while working with the SD card was not due to a single bug, but rather a chain of five architectural and software-related mismatches between FatFs, FreeRTOS, the HAL SPI4 driver, and the hardware
protocol for microSD initialization.

So what, exactly, were those issues ?

Have you now solved them ?

 

The STM32F429 Discovery board doesn’t have a built-in SD card, so please also post full details - including schematic - of how you have connected it.

Some good, clear photos of your setup could help.

Are you sure that none of the on-board features conflicts with your SD card connections?

A complex system that works is invariably found to have evolved from a simple system that worked.A complex system designed from scratch never works and cannot be patched up to make it work.
Associate

There were many errors, and I couldn’t find any trace of a search anywhere. So, I reached a conclusion.

Each of these five issues is analyzed in detail below—this serves as a practical guide that will enable you to write or port a low-level `user_diskio.c` driver for any STM32 project on your own.

0. Increase the stack for the StartDisplayTask task to 1024 words (8192 bytes) in Core/Src/freertos.c

1. Conflict between multithreading and volume mounting (`f_mount` + `_FS_REENTRANT` in FreeRTOS)
• What happened: Calling `f_mount(&sd_fs, "0:", 1)` (with the `opt` parameter set to 1, for immediate mounting) from within a FreeRTOS task—while the `_FS_REENTRANT = 1` option was enabled in `ffconf.h`—caused the system to hang before even entering the disk driver.
• Why this occurs: When `_FS_REENTRANT = 1`, every FatFs function calls `ff_req_grant()` to attempt to acquire an OS mutex/semaphore. In the context of CMSIS-RTOS v2 on STM32, if this call is made early from within a task, the synchronization object may not yet be ready, or it may trigger a deadlock.
• Rules for `diskio.c` and application code:
    • If only one FreeRTOS task accesses the SD card, set `#define _FS_REENTRANT 0` in `ffconf.h`.
    • Use deferred mounting—`f_mount(&sd_fs, USERPath, 0)` (with 0 instead of 1)—so that the actual disk access only occurs when `f_open()` is called.

2. Re-registering the driver (`FATFS_LinkDriver`) and path mismatches (`USERPath`)
• What was happening: The `MX_FATFS_Init()` function, executed at microcontroller startup, had already linked `USER_Driver` and stored the assigned logical drive in the global `USERPath` array (e.g., "0:/" or "1:/", 
if a second interface, such as USB, is enabled in the project). Calling `FATFS_LinkDriver` again created a duplicate drive entry, corrupted the `disk.drv[]` table, and triggered a `HardFault`. Furthermore, using a hardcoded path like "0:/..." 
would result in an `FR_NOT_ENABLED` (`NO_WORKAREA`) error if the driver had actually been linked to "1:/".
• Rule: Never manually call `FATFS_LinkDriver` a second time; always use the `USERPath` system buffer—declared in `fatfs.h`—and concatenate it with the filename (e.g., "1:/RASING1.TXT" or "0:/RASING1.TXT").

3. Avoiding the use of `HAL_SPI_TransmitReceive()` and `HAL_GetTick()` within the SD driver
• What was happening: Within a FreeRTOS task—while high-priority DMA interrupts (I2S2 for audio and SPI5 for the display) are running in parallel—calls to `HAL_SPI_TransmitReceive()` and wait loops based on `HAL_GetTick()` can become prolonged or end up stuck due to `HAL_LOCK` flag contention.
• Rule for `user_diskio.c`: SPI byte exchange within the SD driver should be performed directly via the `SPIx->SR` and `SPIx->DR` registers, using a local timeout counter (set to 1500).
4. Strict SD card initialization protocol via SPI (a mandatory procedure for `USER_initialize`).
Any future `user_diskio.c` you write will reliably support various types of cards (SD v1, SD v2, and SDHC up to 32 GB) provided you strictly follow these 6 steps from the SD SPI standard:
1. Low initial clock speed (100–400 kHz): According to the SD standard, a card cannot operate at megahertz frequencies immediately upon power-up. Start by setting the SPI prescaler to `SPI_BAUDRATEPRESCALER_256` (~312 kHz), and only switch to `SPI_BAUDRATEPRESCALER_16` (~5 MHz) after successful initialization.
2. 80 dummy clock cycles with CS high: Set CS = 1 (`SD_CS_HIGH()`) and send 10 bytes of `0xFF` (80 SCK clock cycles). This transitions the card's controller from the native 4-bit SD mode to SPI mode.
3. Reset to Idle state (CMD0): Set CS = 0 and send the 6-byte sequence `0x40, 0x00, 0x00, 0x00, 0x00, 0x95` (the CRC `0x95` is mandatory for CMD0). The card should respond with `0x01` (In Idle State).
4. Voltage and version check (CMD8): Send CMD8 with an argument of 0x000001AA and a CRC of 0x87.
    • If the card responds with 0x01, read the 4-byte R7 response: if the last two bytes are 0x01 and 0xAA, it is an SD v2 / SDHC card.
    • If the card returns an error (0x05), it is an older SD v1 or MMC card.
5. Exiting sleep mode (ACMD41): Repeatedly send the command pair CMD55 (0x77) + CMD41 (0x69) with an argument of 0x40000000 (the HCS bit for SDHC) until the card returns 0x00 (Ready).
6. Block addressing check (CMD58): For an SD v2 card, read the OCR register using the CMD58 command. If bit 30 (0x40 in the first byte of the response) is 1, the card uses block addressing (CT_BLOCK, where the sector number is passed directly); if it is 0, it uses byte addressing (sector * 512).
5. Hardware Requirements for SD Card SPI Lines

• Pull-up resistor on the MISO line (PE5): Until the card is initialized, its DO (MISO) output remains in a high-impedance (Hi-Z) state. Without a pull-up resistor connected to 3.3V, the controller will read random noise instead of 0xFF.
• FAT32 file system: The standard FatFs library (excluding exFAT support) only works with cards formatted in FAT32. (Note: Cards with a capacity of 64 GB or larger come pre-formatted in exFAT and must therefore be .

At the moment, everything is working reasonably well. I’d like to hear the community’s opinion on this.

Andrew Neil
Super User

 I couldn’t find any trace of a search anywhere. 

Do you mean a forum search ?

It’s here:

That’s for the entire Community

 

Also, in each section:

 

And note the “Sidekick” AI assistant.

 

To be fair, the search isn’t great

 

In a Google search, you can add “site:community.st.com” to your search to have it search only the Community.

I expect other internet search engines have similar “advanced” options?

A complex system that works is invariably found to have evolved from a simple system that worked.A complex system designed from scratch never works and cannot be patched up to make it work.
Associate

 

Andrew Neil
Super User

Better than photographing the screen, use your computer’s screenshot facility.

eg, see: How to get a Windows screenshot.

A complex system that works is invariably found to have evolved from a simple system that worked.A complex system designed from scratch never works and cannot be patched up to make it work.
Associate

 

Associate

I’ve also connected an audio DAC I2S UDA1334A to the board and have sound output via PCM encoding; however, the audio currently suffers from distortions related to DMA.

Associate

Data is loaded from an SD card when the game starts:
SECTOR1_COLOR=0x528A
SECTOR2_COLOR=0xFD20
SECTOR3_COLOR=0x041F
SECTOR4_COLOR=0x2589
CAR_SPEED=4
BARREL_FREQ=45
RIVAL_FREQ=70
SPACE_SECTORS=6
SPACE_ENEMY_SPEED=4
SPACE_ALLY_COUNT=2
There are 4 files in total, all of which are currently loaded from the SD card.
I couldn't find any solutions for the STM32F429Disco board on the forum; there was one old inquiry—with a response and even a video—but it concerned the STM32F429Eval board.
There is nothing to be found online for this specific board either. I wrote the code in collaboration with an AI.
The game currently runs in a multitasking mode, controlled by 3 buttons; it reads configuration data and includes sound effects—though the WAV files (using the PCM codec) suffer from significant distortion.

 

Associate

I have three laptops. One—an older i5 model—is dedicated to CUBE MX and CUBEIDE, and I try not to touch it. I’m using a second one, an i7, to communicate with you, and the third—another i5—serves as my primary work machine. This setup is necessary due to poor internet, unstable power supply (185V) here in Kyiv, the cold temperature in the room, and the demanding nature of the tasks I’m working on.

Associate

 

Associate