2025-01-06 01:39 AM - last edited on 2025-01-06 02:11 AM by SofLit
Subject: SD Card Communication Issue in 4-bit Mode
Iam using STM32F756ZG micro-controller.
I am currently working on interfacing an SD card and have noticed an issue when switching between communication modes. The code executes as expected in 1-bit mode, but it fails when switching to 4-bit mode. Could you please provide insight into why this might be happening and suggest potential solutions to resolve the issue?
Your expertise would be greatly appreciated.
Kind regards,
K.DHARANI
Main.c
#include "main.h"
#include "dma.h"
#include "fatfs.h"
#include "mbedtls.h"
#include "sdmmc.h"
#include "usart.h"
#include "gpio.h"
/* USER CODE BEGIN Includes */
#include<stdio.h>
#include<string.h>
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
FRESULT res; /* FatFs function common result code */
uint32_t byteswritten, bytesread; /* File write/read counts */
uint8_t wtext[] = "Hello from STM32new!"; /* File write buffer */
uint8_t rtext[100]; /* File read buffer */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
int __io_putchar(int ch);
/* Redirecting printf to UART ------------------------------------------------*/
int __io_putchar(int ch)
{
HAL_UART_Transmit(&huart3, (uint8_t *)&ch, 1, HAL_MAX_DELAY);
return ch;
}
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_DMA_Init();
MX_SDMMC1_SD_Init();
MX_USART3_UART_Init();
MX_FATFS_Init();
MX_MBEDTLS_Init();
/* USER CODE BEGIN 2 */
printf("Starting SD card and FatFS test...\n");
/* Mount the file system */
res = f_mount(&SDFatFS, (TCHAR const*)SDPath, 0);
if (res != FR_OK)
{
printf("f_mount error: %d\n", res);
Error_Handler();
}
else
{
printf("File system mounted successfully.\n");
}
/* Open the file for writing */
res = f_open(&SDFile, "ST.TXT", FA_OPEN_APPEND | FA_WRITE);
if (res != FR_OK)
{
printf("f_open error: %d\n", res);
// Error_Handler();
}
else
{
printf("File opened successfully.\n");
/* Write data to the file */
res = f_write(&SDFile, wtext, strlen((char *)wtext), (void *)&byteswritten);
if ((byteswritten == 0) || (res != FR_OK))
{
printf("f_write error: %d\n", res);
// Error_Handler();
}
else
{
printf("Data written successfully. Bytes written: %d\n", byteswritten);
}
/* Close the file */
f_close(&SDFile);
printf("File closed successfully.\n");
}
/* Unmount the file system */
res = f_mount(NULL, (TCHAR const*)SDPath, 0);
if (res == FR_OK)
{
printf("File system unmounted successfully.\n");
}
else
{
printf("f_mount unmount error: %d\n", res);
}
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
HAL_PWR_EnableBkUpAccess();
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_BYPASS;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = 4;
RCC_OscInitStruct.PLL.PLLN = 50;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 3;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK)
{
Error_Handler();
}
}
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
__disable_irq();
while (1)
{
}
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
SDMMC.C
#include "sdmmc.h"
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
SD_HandleTypeDef hsd1;
DMA_HandleTypeDef hdma_sdmmc1_rx;
DMA_HandleTypeDef hdma_sdmmc1_tx;
/* SDMMC1 init function */
void MX_SDMMC1_SD_Init(void)
{
/* USER CODE BEGIN SDMMC1_Init 0 */
/* USER CODE END SDMMC1_Init 0 */
/* USER CODE BEGIN SDMMC1_Init 1 */
/* USER CODE END SDMMC1_Init 1 */
hsd1.Instance = SDMMC1;
hsd1.Init.ClockEdge = SDMMC_CLOCK_EDGE_RISING;
hsd1.Init.ClockBypass = SDMMC_CLOCK_BYPASS_DISABLE;
hsd1.Init.ClockPowerSave = SDMMC_CLOCK_POWER_SAVE_DISABLE;
hsd1.Init.BusWide = SDMMC_BUS_WIDE_4B;
hsd1.Init.HardwareFlowControl = SDMMC_HARDWARE_FLOW_CONTROL_DISABLE;
hsd1.Init.ClockDiv = 4;
/* USER CODE BEGIN SDMMC1_Init 2 */
/* USER CODE END SDMMC1_Init 2 */
}
void HAL_SD_MspInit(SD_HandleTypeDef* sdHandle)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0};
if(sdHandle->Instance==SDMMC1)
{
/* USER CODE BEGIN SDMMC1_MspInit 0 */
/* USER CODE END SDMMC1_MspInit 0 */
/** Initializes the peripherals clock
*/
PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_SDMMC1;
PeriphClkInitStruct.Sdmmc1ClockSelection = RCC_SDMMC1CLKSOURCE_SYSCLK;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK)
{
Error_Handler();
}
/* SDMMC1 clock enable */
__HAL_RCC_SDMMC1_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
/**SDMMC1 GPIO Configuration
PC8 ------> SDMMC1_D0
PC9 ------> SDMMC1_D1
PC10 ------> SDMMC1_D2
PC11 ------> SDMMC1_D3
PC12 ------> SDMMC1_CK
PD2 ------> SDMMC1_CMD
*/
GPIO_InitStruct.Pin = GPIO_PIN_8|GPIO_PIN_9|GPIO_PIN_10|GPIO_PIN_11
|GPIO_PIN_12;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF12_SDMMC1;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_2;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF12_SDMMC1;
HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
/* SDMMC1 DMA Init */
/* SDMMC1_RX Init */
hdma_sdmmc1_rx.Instance = DMA2_Stream3;
hdma_sdmmc1_rx.Init.Channel = DMA_CHANNEL_4;
hdma_sdmmc1_rx.Init.Direction = DMA_PERIPH_TO_MEMORY;
hdma_sdmmc1_rx.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_sdmmc1_rx.Init.MemInc = DMA_MINC_ENABLE;
hdma_sdmmc1_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_WORD;
hdma_sdmmc1_rx.Init.MemDataAlignment = DMA_MDATAALIGN_WORD;
hdma_sdmmc1_rx.Init.Mode = DMA_PFCTRL;
hdma_sdmmc1_rx.Init.Priority = DMA_PRIORITY_LOW;
hdma_sdmmc1_rx.Init.FIFOMode = DMA_FIFOMODE_ENABLE;
hdma_sdmmc1_rx.Init.FIFOThreshold = DMA_FIFO_THRESHOLD_FULL;
hdma_sdmmc1_rx.Init.MemBurst = DMA_MBURST_INC4;
hdma_sdmmc1_rx.Init.PeriphBurst = DMA_PBURST_INC4;
if (HAL_DMA_Init(&hdma_sdmmc1_rx) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(sdHandle,hdmarx,hdma_sdmmc1_rx);
/* SDMMC1_TX Init */
hdma_sdmmc1_tx.Instance = DMA2_Stream6;
hdma_sdmmc1_tx.Init.Channel = DMA_CHANNEL_4;
hdma_sdmmc1_tx.Init.Direction = DMA_MEMORY_TO_PERIPH;
hdma_sdmmc1_tx.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_sdmmc1_tx.Init.MemInc = DMA_MINC_ENABLE;
hdma_sdmmc1_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_WORD;
hdma_sdmmc1_tx.Init.MemDataAlignment = DMA_MDATAALIGN_WORD;
hdma_sdmmc1_tx.Init.Mode = DMA_PFCTRL;
hdma_sdmmc1_tx.Init.Priority = DMA_PRIORITY_LOW;
hdma_sdmmc1_tx.Init.FIFOMode = DMA_FIFOMODE_ENABLE;
hdma_sdmmc1_tx.Init.FIFOThreshold = DMA_FIFO_THRESHOLD_FULL;
hdma_sdmmc1_tx.Init.MemBurst = DMA_MBURST_INC4;
hdma_sdmmc1_tx.Init.PeriphBurst = DMA_PBURST_INC4;
if (HAL_DMA_Init(&hdma_sdmmc1_tx) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(sdHandle,hdmatx,hdma_sdmmc1_tx);
/* SDMMC1 interrupt Init */
HAL_NVIC_SetPriority(SDMMC1_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(SDMMC1_IRQn);
/* USER CODE BEGIN SDMMC1_MspInit 1 */
/* USER CODE END SDMMC1_MspInit 1 */
}
}
void HAL_SD_MspDeInit(SD_HandleTypeDef* sdHandle)
{
if(sdHandle->Instance==SDMMC1)
{
/* USER CODE BEGIN SDMMC1_MspDeInit 0 */
/* USER CODE END SDMMC1_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_SDMMC1_CLK_DISABLE();
/**SDMMC1 GPIO Configuration
PC8 ------> SDMMC1_D0
PC9 ------> SDMMC1_D1
PC10 ------> SDMMC1_D2
PC11 ------> SDMMC1_D3
PC12 ------> SDMMC1_CK
PD2 ------> SDMMC1_CMD
*/
HAL_GPIO_DeInit(GPIOC, GPIO_PIN_8|GPIO_PIN_9|GPIO_PIN_10|GPIO_PIN_11
|GPIO_PIN_12);
HAL_GPIO_DeInit(GPIOD, GPIO_PIN_2);
/* SDMMC1 DMA DeInit */
HAL_DMA_DeInit(sdHandle->hdmarx);
HAL_DMA_DeInit(sdHandle->hdmatx);
/* SDMMC1 interrupt Deinit */
HAL_NVIC_DisableIRQ(SDMMC1_IRQn);
/* USER CODE BEGIN SDMMC1_MspDeInit 1 */
/* USER CODE END SDMMC1_MspDeInit 1 */
}
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
DMA.C
#include "dma.h"
__HAL_RCC_DMA2_CLK_ENABLE();
/* DMA interrupt init */
/* DMA2_Stream3_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA2_Stream3_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA2_Stream3_IRQn);
/* DMA2_Stream6_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA2_Stream6_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA2_Stream6_IRQn);
}
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */
FATFS_PLATFORM.C
/* USER CODE END Header */
#include "fatfs_platform.h"
uint8_t BSP_PlatformIsDetected(void) {
uint8_t status = SD_PRESENT;
/* Check SD card detect pin */
// if(HAL_GPIO_ReadPin(SD_DETECT_GPIO_PORT, SD_DETECT_PIN) != GPIO_PIN_RESET)
// {
// status = SD_NOT_PRESENT;
// }
/* USER CODE BEGIN 1 */
/* user code can be inserted here */
/* USER CODE END 1 */
return status;
}
BSP_DRIVER_SD.C
#ifdef OLD_API
/* kept to avoid issue when migrating old projects. */
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
#else
/* USER CODE BEGIN FirstSection */
/* can be used to modify / undefine following code or add new definitions */
/* USER CODE END FirstSection */
/* Includes ------------------------------------------------------------------*/
#include "bsp_driver_sd.h"
/* Extern variables ---------------------------------------------------------*/
extern SD_HandleTypeDef hsd1;
/* USER CODE BEGIN BeforeInitSection */
/* can be used to modify / undefine following code or add code */
/* USER CODE END BeforeInitSection */
/**
* @brief Initializes the SD card device.
* @retval SD status
*/
__weak uint8_t BSP_SD_Init(void)
{
uint8_t sd_state = MSD_OK;
/* Check if the SD card is plugged in the slot */
if (BSP_SD_IsDetected() != SD_PRESENT)
{
return MSD_ERROR_SD_NOT_PRESENT;
}
/* HAL SD initialization */
sd_state = HAL_SD_Init(&hsd1);
/* Configure SD Bus width (4 bits mode selected) */
if (sd_state == MSD_OK)
{
/* Enable wide operation */
if (HAL_SD_ConfigWideBusOperation(&hsd1, SDMMC_BUS_WIDE_4B) != HAL_OK)
{
sd_state = MSD_ERROR;
}
}
return sd_state;
}
__weak uint8_t BSP_SD_ITConfig(void)
{
/* Code to be updated by the user or replaced by one from the FW pack (in a stmxxxx_sd.c file) */
return (uint8_t)0;
}
/* USER CODE END InterruptMode */
__weak uint8_t BSP_SD_ReadBlocks(uint32_t *pData, uint32_t ReadAddr, uint32_t NumOfBlocks, uint32_t Timeout)
{
uint8_t sd_state = MSD_OK;
if (HAL_SD_ReadBlocks(&hsd1, (uint8_t *)pData, ReadAddr, NumOfBlocks, Timeout) != HAL_OK)
{
sd_state = MSD_ERROR;
}
return sd_state;
}
__weak uint8_t BSP_SD_WriteBlocks(uint32_t *pData, uint32_t WriteAddr, uint32_t NumOfBlocks, uint32_t Timeout)
{
uint8_t sd_state = MSD_OK;
if (HAL_SD_WriteBlocks(&hsd1, (uint8_t *)pData, WriteAddr, NumOfBlocks, Timeout) != HAL_OK)
{
sd_state = MSD_ERROR;
}
return sd_state;
}
__weak uint8_t BSP_SD_ReadBlocks_DMA(uint32_t *pData, uint32_t ReadAddr, uint32_t NumOfBlocks)
{
uint8_t sd_state = MSD_OK;
/* Read block(s) in DMA transfer mode */
if (HAL_SD_ReadBlocks_DMA(&hsd1, (uint8_t *)pData, ReadAddr, NumOfBlocks) != HAL_OK)
{
sd_state = MSD_ERROR;
}
return sd_state;
}
__weak uint8_t BSP_SD_WriteBlocks_DMA(uint32_t *pData, uint32_t WriteAddr, uint32_t NumOfBlocks)
{
uint8_t sd_state = MSD_OK;
/* Write block(s) in DMA transfer mode */
if (HAL_SD_WriteBlocks_DMA(&hsd1, (uint8_t *)pData, WriteAddr, NumOfBlocks) != HAL_OK)
{
sd_state = MSD_ERROR;
}
return sd_state;}
__weak uint8_t BSP_SD_Erase(uint32_t StartAddr, uint32_t EndAddr)
{
uint8_t sd_state = MSD_OK;
if (HAL_SD_Erase(&hsd1, StartAddr, EndAddr) != HAL_OK)
{
sd_state = MSD_ERROR;
}
return sd_state;
}
__weak uint8_t BSP_SD_GetCardState(void)
{
return ((HAL_SD_GetCardState(&hsd1) == HAL_SD_CARD_TRANSFER ) ? SD_TRANSFER_OK : SD_TRANSFER_BUSY);
}
__weak void BSP_SD_GetCardInfo(HAL_SD_CardInfoTypeDef *CardInfo)
{
/* Get SD card Information */
HAL_SD_GetCardInfo(&hsd1, CardInfo);
}
void HAL_SD_AbortCallback(SD_HandleTypeDef *hsd)
{
BSP_SD_AbortCallback();
}
void HAL_SD_TxCpltCallback(SD_HandleTypeDef *hsd)
{
BSP_SD_WriteCpltCallback();
}
void HAL_SD_RxCpltCallback(SD_HandleTypeDef *hsd)
{
BSP_SD_ReadCpltCallback();
}
__weak void BSP_SD_AbortCallback(void)
{
}
__weak void BSP_SD_WriteCpltCallback(void)
{
}
__weak void BSP_SD_ReadCpltCallback(void)
{
}
/* USER CODE END CallBacksSection_C */
#endif
__weak uint8_t BSP_SD_IsDetected(void)
{
__IO uint8_t status = SD_PRESENT;
if (BSP_PlatformIsDetected() == 0x0)
{
status = SD_NOT_PRESENT;
}
return status;
}
SD_DISKIO.C
/* USER CODE BEGIN Header */
/* USER CODE END Header */
/* Note: code generation based on sd_diskio_dma_template_bspv1.c v2.1.4
as "Use dma template" is enabled. */
/* USER CODE BEGIN firstSection */
/* can be used to modify / undefine following code or add new definitions */
/* USER CODE END firstSection*/
/* Includes ------------------------------------------------------------------*/
#include "ff_gen_drv.h"
#include "sd_diskio.h"
#include <string.h>
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define SD_TIMEOUT 30 * 1000
#define SD_DEFAULT_BLOCK_SIZE 512
#if defined(ENABLE_SCRATCH_BUFFER)
#if defined (ENABLE_SD_DMA_CACHE_MAINTENANCE)
ALIGN_32BYTES(static uint8_t scratch[BLOCKSIZE]); // 32-Byte aligned for cache maintenance
#else
__ALIGN_BEGIN static uint8_t scratch[BLOCKSIZE] __ALIGN_END;
#endif
#endif
/* Disk status */
static volatile DSTATUS Stat = STA_NOINIT;
static volatile UINT WriteStatus = 0, ReadStatus = 0;
/* Private function prototypes -----------------------------------------------*/
static DSTATUS SD_CheckStatus(BYTE lun);
DSTATUS SD_initialize (BYTE);
DSTATUS SD_status (BYTE);
DRESULT SD_read (BYTE, BYTE*, DWORD, UINT);
#if _USE_WRITE == 1
DRESULT SD_write (BYTE, const BYTE*, DWORD, UINT);
#endif /* _USE_WRITE == 1 */
#if _USE_IOCTL == 1
DRESULT SD_ioctl (BYTE, BYTE, void*);
#endif /* _USE_IOCTL == 1 */
const Diskio_drvTypeDef SD_Driver =
{
SD_initialize,
SD_status,
SD_read,
#if _USE_WRITE == 1
SD_write,
#endif /* _USE_WRITE == 1 */
#if _USE_IOCTL == 1
SD_ioctl,
#endif /* _USE_IOCTL == 1 */
};
/* USER CODE BEGIN beforeFunctionSection */
/* can be used to modify / undefine following code or add new code */
/* USER CODE END beforeFunctionSection */
/* Private functions ---------------------------------------------------------*/
static int SD_CheckStatusWithTimeout(uint32_t timeout)
{
uint32_t timer = HAL_GetTick();
/* block until SDIO IP is ready again or a timeout occur */
while(HAL_GetTick() - timer < timeout)
{
if (BSP_SD_GetCardState() == SD_TRANSFER_OK)
{
return 0;
}
}
return -1;
}
static DSTATUS SD_CheckStatus(BYTE lun)
{
Stat = STA_NOINIT;
if(BSP_SD_GetCardState() == MSD_OK)
{
Stat &= ~STA_NOINIT;
}
return Stat;
}
/**
* @brief Initializes a Drive
* lun : not used
* @retval DSTATUS: Operation status
*/
DSTATUS SD_initialize(BYTE lun)
{
#if !defined(DISABLE_SD_INIT)
if(BSP_SD_Init() == MSD_OK)
{
Stat = SD_CheckStatus(lun);
}
#else
Stat = SD_CheckStatus(lun);
#endif
return Stat;
}
/**
* @brief Gets Disk Status
* lun : not used
* @retval DSTATUS: Operation status
*/
DSTATUS SD_status(BYTE lun)
{
return SD_CheckStatus(lun);
}
/* USER CODE BEGIN beforeReadSection */
/* can be used to modify previous code / undefine following code / add new code */
/* USER CODE END beforeReadSection */
/**
* @brief Reads Sector(s)
* lun : not used
* *buff: Data buffer to store read data
* sector: Sector address (LBA)
* count: Number of sectors to read (1..128)
* @retval DRESULT: Operation result
*/
DRESULT SD_read(BYTE lun, BYTE *buff, DWORD sector, UINT count)
{
DRESULT res = RES_ERROR;
uint32_t timeout;
#if defined(ENABLE_SCRATCH_BUFFER)
uint8_t ret;
#endif
#if (ENABLE_SD_DMA_CACHE_MAINTENANCE == 1)
uint32_t alignedAddr;
#endif
/*
* ensure the SDCard is ready for a new operation
*/
if (SD_CheckStatusWithTimeout(SD_TIMEOUT) < 0)
{
return res;
}
#if defined(ENABLE_SCRATCH_BUFFER)
if (!((uint32_t)buff & 0x3))
{
#endif
if(BSP_SD_ReadBlocks_DMA((uint32_t*)buff,
(uint32_t) (sector),
count) == MSD_OK)
{
ReadStatus = 0;
/* Wait that the reading process is completed or a timeout occurs */
timeout = HAL_GetTick();
while((ReadStatus == 0) && ((HAL_GetTick() - timeout) < SD_TIMEOUT))
{
}
/* in case of a timeout return error */
if (ReadStatus == 0)
{
res = RES_ERROR;
}
else
{
ReadStatus = 0;
timeout = HAL_GetTick();
while((HAL_GetTick() - timeout) < SD_TIMEOUT)
{
if (BSP_SD_GetCardState() == SD_TRANSFER_OK)
{
res = RES_OK;
#if (ENABLE_SD_DMA_CACHE_MAINTENANCE == 1)
/*
the SCB_InvalidateDCache_by_Addr() requires a 32-Byte aligned address,
adjust the address and the D-Cache size to invalidate accordingly.
*/
alignedAddr = (uint32_t)buff & ~0x1F;
SCB_InvalidateDCache_by_Addr((uint32_t*)alignedAddr, count*BLOCKSIZE + ((uint32_t)buff - alignedAddr));
#endif
break;
}
}
}
}
#if defined(ENABLE_SCRATCH_BUFFER)
}
else
{
/* Slow path, fetch each sector a part and memcpy to destination buffer */
int i;
for (i = 0; i < count; i++) {
ret = BSP_SD_ReadBlocks_DMA((uint32_t*)scratch, (uint32_t)sector++, 1);
if (ret == MSD_OK) {
/* wait until the read is successful or a timeout occurs */
timeout = HAL_GetTick();
while((ReadStatus == 0) && ((HAL_GetTick() - timeout) < SD_TIMEOUT))
{
}
if (ReadStatus == 0)
{
res = RES_ERROR;
break;
}
ReadStatus = 0;
#if (ENABLE_SD_DMA_CACHE_MAINTENANCE == 1)
/*
*
* invalidate the scratch buffer before the next read to get the actual data instead of the cached one
*/
SCB_InvalidateDCache_by_Addr((uint32_t*)scratch, BLOCKSIZE);
#endif
memcpy(buff, scratch, BLOCKSIZE);
buff += BLOCKSIZE;
}
else
{
break;
}
}
if ((i == count) && (ret == MSD_OK))
res = RES_OK;
}
#endif
return res;
}
/* USER CODE BEGIN beforeWriteSection */
/* can be used to modify previous code / undefine following code / add new code */
/* USER CODE END beforeWriteSection */
/**
* @brief Writes Sector(s)
* lun : not used
* *buff: Data to be written
* sector: Sector address (LBA)
* count: Number of sectors to write (1..128)
* @retval DRESULT: Operation result
*/
#if _USE_WRITE == 1
DRESULT SD_write(BYTE lun, const BYTE *buff, DWORD sector, UINT count)
{
DRESULT res = RES_ERROR;
uint32_t timeout;
#if defined(ENABLE_SCRATCH_BUFFER)
uint8_t ret;
int i;
#endif
WriteStatus = 0;
#if (ENABLE_SD_DMA_CACHE_MAINTENANCE == 1)
uint32_t alignedAddr;
#endif
if (SD_CheckStatusWithTimeout(SD_TIMEOUT) < 0)
{
return res;
}
#if defined(ENABLE_SCRATCH_BUFFER)
if (!((uint32_t)buff & 0x3))
{
#endif
#if (ENABLE_SD_DMA_CACHE_MAINTENANCE == 1)
/*
the SCB_CleanDCache_by_Addr() requires a 32-Byte aligned address
adjust the address and the D-Cache size to clean accordingly.
*/
alignedAddr = (uint32_t)buff & ~0x1F;
SCB_CleanDCache_by_Addr((uint32_t*)alignedAddr, count*BLOCKSIZE + ((uint32_t)buff - alignedAddr));
#endif
if(BSP_SD_WriteBlocks_DMA((uint32_t*)buff,
(uint32_t)(sector),
count) == MSD_OK)
{
/* Wait that writing process is completed or a timeout occurs */
timeout = HAL_GetTick();
while((WriteStatus == 0) && ((HAL_GetTick() - timeout) < SD_TIMEOUT))
{
}
/* in case of a timeout return error */
if (WriteStatus == 0)
{
res = RES_ERROR;
}
else
{
WriteStatus = 0;
timeout = HAL_GetTick();
while((HAL_GetTick() - timeout) < SD_TIMEOUT)
{
if (BSP_SD_GetCardState() == SD_TRANSFER_OK)
{
res = RES_OK;
break;
}
}
}
}
#if defined(ENABLE_SCRATCH_BUFFER)
}
else
{
/* Slow path, fetch each sector a part and memcpy to destination buffer */
#if (ENABLE_SD_DMA_CACHE_MAINTENANCE == 1)
/*
* invalidate the scratch buffer before the next write to get the actual data instead of the cached one
*/
SCB_InvalidateDCache_by_Addr((uint32_t*)scratch, BLOCKSIZE);
#endif
for (i = 0; i < count; i++)
{
WriteStatus = 0;
memcpy((void *)scratch, (void *)buff, BLOCKSIZE);
buff += BLOCKSIZE;
ret = BSP_SD_WriteBlocks_DMA((uint32_t*)scratch, (uint32_t)sector++, 1);
if (ret == MSD_OK) {
/* wait for a message from the queue or a timeout */
timeout = HAL_GetTick();
while((WriteStatus == 0) && ((HAL_GetTick() - timeout) < SD_TIMEOUT))
{
}
if (WriteStatus == 0)
{
break;
}
}
else
{
break;
}
}
if ((i == count) && (ret == MSD_OK))
res = RES_OK;
}
#endif
return res;
}
#endif /* _USE_WRITE == 1 */
/* USER CODE BEGIN beforeIoctlSection */
/* can be used to modify previous code / undefine following code / add new code */
/* USER CODE END beforeIoctlSection */
/**
* @brief I/O control operation
* lun : not used
* cmd: Control code
* *buff: Buffer to send/receive control data
* @retval DRESULT: Operation result
*/
#if _USE_IOCTL == 1
DRESULT SD_ioctl(BYTE lun, BYTE cmd, void *buff)
{
DRESULT res = RES_ERROR;
BSP_SD_CardInfo CardInfo;
if (Stat & STA_NOINIT) return RES_NOTRDY;
switch (cmd)
{
/* Make sure that no pending write process */
case CTRL_SYNC :
res = RES_OK;
break;
/* Get number of sectors on the disk (DWORD) */
case GET_SECTOR_COUNT :
BSP_SD_GetCardInfo(&CardInfo);
*(DWORD*)buff = CardInfo.LogBlockNbr;
res = RES_OK;
break;
/* Get R/W sector size (WORD) */
case GET_SECTOR_SIZE :
BSP_SD_GetCardInfo(&CardInfo);
*(WORD*)buff = CardInfo.LogBlockSize;
res = RES_OK;
break;
/* Get erase block size in unit of sector (DWORD) */
case GET_BLOCK_SIZE :
BSP_SD_GetCardInfo(&CardInfo);
*(DWORD*)buff = CardInfo.LogBlockSize / SD_DEFAULT_BLOCK_SIZE;
res = RES_OK;
break;
default:
res = RES_PARERR;
}
return res;
}
#endif /* _USE_IOCTL == 1 */
/* USER CODE BEGIN afterIoctlSection */
/* can be used to modify previous code / undefine following code / add new code */
/* USER CODE END afterIoctlSection */
/* USER CODE BEGIN callbackSection */
/* can be used to modify / following code or add new code */
/* USER CODE END callbackSection */
/**
* @brief Tx Transfer completed callbacks
* hsd: SD handle
* @retval None
*/
void BSP_SD_WriteCpltCallback(void)
{
WriteStatus = 1;
}
/**
* @brief Rx Transfer completed callbacks
* hsd: SD handle
* @retval None
*/
void BSP_SD_ReadCpltCallback(void)
{
ReadStatus = 1;
}
/* USER CODE BEGIN ErrorAbortCallbacks */
/*
==============================================================================================
depending on the SD_HAL_Driver version, either the HAL_SD_ErrorCallback() or HAL_SD_AbortCallback()
or both could be defined, activate the callbacks below when suitable and needed
==============================================================================================
void BSP_SD_AbortCallback(void)
{
}
void BSP_SD_ErrorCallback(void)
{
}
*/
/* USER CODE END ErrorAbortCallbacks */
/* USER CODE BEGIN lastSection */
/* can be used to modify / undefine previous code or add new code */
/* USER CODE END lastSection */
FATFS.C
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file fatfs.c
* @brief Code for fatfs applications
******************************************************************************
* @attention
*
* Copyright (c) 2025 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
#include "fatfs.h"
uint8_t retSD; /* Return value for SD */
char SDPath[4]; /* SD logical drive path */
FATFS SDFatFS; /* File system object for SD logical drive */
FIL SDFile; /* File object for SD */
/* USER CODE BEGIN Variables */
/* USER CODE END Variables */
void MX_FATFS_Init(void)
{
/*## FatFS: Link the SD driver ###########################*/
retSD = FATFS_LinkDriver(&SD_Driver, SDPath);
/* USER CODE BEGIN Init */
/* additional user code for init */
/* USER CODE END Init */
}
/**
* @brief Gets Time from RTC
* None
* @retval Time in DWORD
*/
DWORD get_fattime(void)
{
/* USER CODE BEGIN get_fattime */
return 0;
/* USER CODE END get_fattime */
}
/* USER CODE BEGIN Application */
/* USER CODE END Application */
2025-01-06 01:42 AM
Hello,
See this thread.
2025-01-06 12:02 PM
That's not an acceptable solution, it's a punt!
Stop being so lazy and provide an actual consolidated UPDATED step-by-step solution that is in one place - as opposed to referring to 2 year old links that are based on older firmware.
Of course, the better option would be to fix STM32CubeMX.
BTW, similar issue here on STM32H757. Cannot get SDMMC1 to work with FatFs - with and without MDMA.
2025-01-06 02:04 PM
Hello dharanik_1399,
Out of curiousity, what have you got the MAX_SS set to - in your FatFS settings?
2025-01-06 02:52 PM - edited 2025-01-06 02:53 PM
MAX_SS of 512 should be fine of 512-byte sector'd eMMC and SD Cards. Would want 4KB for QSPI NOR Flash based file system.
I'd probably not configure pins as VERY_HIGH speed, apt to get a lot of ringing. With 4-bit mode it's going to be quite sensitive to stubs in the PCB, can be problematic on the NUCLEO-144 boards, although not specific board or design was mentioned by the OP. Many have SB to remove larger stubs.
Also how it's socketed/wired. The SDMMC/SDIO peripheral and cards are going to be sensitive to relative bit slewing across 4-bit vs clock edge.
There's a systemic race issue on ReadStatus in the OP's code (perhaps inherited from ST), and perhaps a caching issue based on 32-byte alignment of cachelines, and InvalidateDCache throwing things away
2025-01-06 07:20 PM
Hello Tesla DeLorean,
Not sure that the selection in CubeMX even matters as the created sd_diskio.c is initiated with:
#define SD_DEFAULT_BLOCK_SIZE 512
The SD was formatted with 4096 sectors and was initially configured in CubeMX as such; however, later 512 in CubeMX made the code magically work. Later, reverted back to 4096 (in .ioc) and the generated code still compiled and worked.
IMO, this is a mismatch and there is a bug somewhere that ought to be corrected.
Thank you for the reply.