1
\$\begingroup\$

I am practicing the microSD card on a PCB board with the STM32F405 chip. The testing program is generated by STM32CubeMX. The code is very easy to understand.

The problem is that an error happens when it goes to file open. But the weird thing is that if I reset the chip by pulling the NRST pin to low manually, the chip restarts and works smoothly.

Any clue?

/* Reset of all peripherals, initializes the flash interface, and the Systick. */
HAL_Init();

/* Configure the system clock */
SystemClock_Config();

/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_DMA_Init();
MX_SDIO_SD_Init();
MX_TIM9_Init();
//MX_FATFS_Init();  // We call FATFS_LinkDriver directly to initialize the fatfs
MX_USB_DEVICE_Init();
TimeDelay_Init();


/* USER CODE BEGIN 2 */

GREEN_LED_ON;RED_LED_ON;
TM_DelayMillis(500);
GREEN_LED_OFF;RED_LED_OFF;
TM_DelayMillis(1000);


/* USER CODE BEGIN 2 */

// Before it starts,  wait for computer to connect
while(SHIFT_BUTTON==1){ // Wait for the shift button to be pushed
    ;
}

/* USER CODE END 2 */


/* Infinite loop */

/* USER CODE BEGIN WHILE */
FRESULT res;                                           /* FatFs function common result code */
uint32_t byteswritten, bytesread, byteswrittentotal;   /* File write/read counts */
uint8_t rtext[200];
char textbuf[200]; //string buffer
char filename[]="fileW4.txt"; // Filename length should be <= 8   /* File read buffer */


/* ##-1- Link the microSD disk I/O driver ################################## */
if(FATFS_LinkDriver(&SD_Driver, SD_Path) == 0) // We call FATFS_LinkDriver directly to initialize the fatfs
{
    sprintf(usbbuffer, "\n---FATFS_LinkDriver OK ---\n");//export it to char buffer first.
    SendTextMsgToUSB(usbbuffer); // Send the txt back

    /* ##-2- Register the file system object to the FatFs module ############## */
    if(f_mount(&SDFatFs, (TCHAR const*)SD_Path, 0) != FR_OK)
    {
        /* FatFs Initialization Error */
        sprintf(usbbuffer, "\n---f_mount error ---\n"); // Export it to char buffer first.
        SendTextMsgToUSB(usbbuffer);  // Send the txt back

        Error_Handler();
    }
    else
    {
        /* ##-3- Create a FAT file system (format) on the logical drive ######### */
        /* WARNING: Formatting the uSD card will delete all content on the device */
        //   if(f_mkfs((TCHAR const*)SDPath, 0, 0) != FR_OK) // No need to format, so comment it
        //f_mkfs((TCHAR const*)SDPath, 0, 0);
        sprintf(usbbuffer, "\n---ready to open file ---\n"); // Export it to char buffer first.
        SendTextMsgToUSB(usbbuffer); // Send the txt back

        /* ##-4- Create and Open a new text file object with write access ##### */
        res=f_open(&MyFile, filename, FA_CREATE_ALWAYS | FA_WRITE);
        if (res!= FR_OK)
        {
            /* 'STM32.TXT' file Open for write Error */
            sprintf(usbbuffer, "\n---Open file error ---\n");//export it to char buffer first.
            SendTextMsgToUSB(usbbuffer);  //send the txt back

            Error_Handler();
        }
        else
        {
            /* ##-5- Write data to the text file ################################ */
            sprintf(usbbuffer, "\n---File is open. Ready to write contents ---\n"); // Export it to char buffer first.
            SendTextMsgToUSB(usbbuffer);  // Send the txt back

            // Write capacity info as testing
            BSP_SD_GetCardInfo(&uSdCardInfotmp);
            sprintf(textbuf, "\nThe capacity of the card is:%"PRIu64"B\nThis is for file:%s", uSdCardInfotmp.CardCapacity,filename); // Export it to char buffer first. In this way, no null symbol
            res=f_write(&MyFile, textbuf, strlen(textbuf), (void *)&byteswritten);
            if((byteswritten == 0) || (res != FR_OK))
            {
                /* 'STM32.TXT' file Write or EOF Error */
                Error_Handler();
            }
            sprintf(usbbuffer, "\n---First line was written %s ---\n", textbuf); // Export it to char buffer first.
            SendTextMsgToUSB(usbbuffer);  // Send the txt back

            // Now we test the fast file writing of small bytes.
            unsigned char testtimer=0;
            for(int i=0; i<20000; i++)
            {
                sprintf(textbuf, "i=%d,data=%d\n", i, i); // Export it to char buffer first.
                uint32_t bytecount=MyWriteToFile(&MyFile, textbuf, strlen(textbuf));
                byteswritten += bytecount;
                if(bytecount==0){
                    f_close(&MyFile);Error_Handler();
                }
            }
            byteswritten += MyFlushDatatoFile(&MyFile); // Close file

            f_close(&MyFile);
            sprintf(usbbuffer, "\n---File is closed ---\n"); // Export it to char buffer first.
            SendTextMsgToUSB(usbbuffer);  // Send the txt back

            GREEN_LED_ON;
        }
    }
}

/* ##-11- Unlink the RAM disk I/O driver #################################### */
FATFS_UnLinkDriver(SD_Path);
\$\endgroup\$
  • 1
    \$\begingroup\$ What errors happen? Please describe them with a lot more details. \$\endgroup\$ – Turbo J Jan 13 '17 at 21:51
  • \$\begingroup\$ initialization of disk error in the first run. After I reset the chip, no problem at all. \$\endgroup\$ – william Jan 15 '17 at 6:24
  • \$\begingroup\$ Can you single-step this program (in a debugger)? Exactly which line is it failing at? Is the STM32F405 on an evaluation board? If yes, which one? \$\endgroup\$ – Peter Mortensen Jan 15 '17 at 18:15
  • \$\begingroup\$ in fopen(), dig into it, error happens in find_volume(&dj.fs, &path, (BYTE)(mode & ~FA_READ));. \$\endgroup\$ – william Jan 15 '17 at 18:58
  • \$\begingroup\$ Chances are at some point in the sequence of necessary operations your program is going ahead without checking that the card is ready; when you reset the MCU, the second attempt lucks out that it is. You'll need to go through all the SD operations to figure out which one is unsafely proceeding without confirmation. \$\endgroup\$ – Chris Stratton Jan 15 '17 at 20:06
2
\$\begingroup\$

Afer some testing and searching, I found the problem. It is a bug in the file generated by cubemx. Here is the details.

  1. Pack version: STM32Cube_FW_F4_V1.13.0, Cubemx 4.16.1. The uSD card I tested is 1GB made in japan.
  2. The lib for microSD and file is generated by cubemx wizard.
  3. I tested the microSD on the chip STM32F405RGT6 . .
  4. The problem I confronted is that initialization of sd card always fails, but everything goes through smoothly if I reset the chip(via nrst). Weird? Make the story short. Initialization of SD card fails in the function: SD_PowerON(SD_HandleTypeDef *hsd) with error code SD_COM_CRC_FAILED. Note the function is defined in the file: stm32f4xx_hal_sd.c
  5. I moved the HAL_Delay(1) to after clock_enable in the function SD_PowerON , everything is working well.

If you want to read more details, please read the thread:https://community.st.com/thread/34299-microsd-card-problem

Here is the code:

static HAL_SD_ErrorTypedef SD_PowerON(SD_HandleTypeDef *hsd)
{
  SDIO_CmdInitTypeDef sdio_cmdinitstructure; 
  __IO HAL_SD_ErrorTypedef errorstate = SD_OK; 
  uint32_t response = 0U, count = 0U, validvoltage = 0U;
  uint32_t sdtype = SD_STD_CAPACITY;

  /* Power ON Sequence -------------------------------------------------------*/
  /* Disable SDIO Clock */
  __HAL_SD_SDIO_DISABLE(); 

  /* Set Power State to ON */
  SDIO_PowerState_ON(hsd->Instance);

 /* 1ms: required power up waiting time before starting the SD initialization 
 sequence */
 // HAL_Delay(1); //should be after __HAL_SD_SDIO_ENABLE()

 /* Enable SDIO Clock */
 __HAL_SD_SDIO_ENABLE();
//moved to here
 /* 1ms: required power up waiting time before starting the SD initialization 
 sequence */
 HAL_Delay(1); 
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.