How to use CubeMx to create a file system project based on SD card

Publisher:星辰耀眼Latest update time:2016-12-27 Source: eefocusKeywords:CubeMx Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

1 Introduction

This article will introduce how to use the CubeMx tool to create an SD card-based file system from scratch, for reference by those who will use this function in the future.

2 Preparation

The test of this project will use the STM3240G-EVAL, the official evaluation board of ST, as the test platform. It is necessary to first understand the connection methods of some external components of this board.

LED Circuit 
Button circuit 
LED1~LED4 use pins PG6, PG8, PI9, PC7 respectively, output high level LED lights, user button uses PG15 pin, when pressed, it is low level. 
HSE Circuit 
SD card circuit 
As shown in the figure above, the HSE used by MCU is 25M crystal oscillator. SD card uses 6 fixed pins of STM32F407 as shown in the figure above: D0 (PC8), D1 (PC9), D2 (PC10), D3 (PC11), CLK (PC12), CMD (PD2). The SD card insertion detection pin is a user-defined pin, and the PH13 pin is used on the STM3240G, the official evaluation board of ST.

3. Create CubeMx project and modify code

3.1 Create CubeMx project

Open CubeMx and create a project based on STM32F407IGHx, enable HSE of RCC, external crystal mode, and SDIO uses 4-bit bus width, as shown in the figure below: 
RCC 
SDIO 
Set PH13 to INPUT mode on the right side of pinout: 
pinout 
Next, configure the clock tree and configure the main screen to 168M: 
clock tree
The configuration on the configuration page is shown in the figure below: 
configuration 
Add SD Card type FATFS in the middleware: 
middleware 
Use the default parameter values ​​for the file system related parameter configurations in the configuration. 
Another very important point is to configure the stack size to 0x800 in the project settings. The default 0x400 is not enough and an error will occur during runtime. As shown below: 
Project settings 
Finally, click Generate Code.

3.2 SD card and file system initialization

The main function contains the following code:

  MX_GPIO_Init(); MX_SDIO_SD_Init(); MX_FATFS_Init();12341234

The SDIO initialization code has been automatically generated. No modification is required. Enter the MX_FATFS_Init() function and add user-defined code between /* USER CODE BEGIN Init / and / USER CODE END Init */ as follows:

/* USER CODE BEGIN Variables */FATFS SDFatFs;/* USER CODE END Variables */ void MX_FATFS_Init(void)
{ /*## FatFS: Link the SD driver ###########################*/
  retSD = FATFS_LinkDriver(&SD_Driver, SD_Path); /* USER CODE BEGIN Init */
  /* additional user code for init */
    if(f_mount(&SDFatFs, (TCHAR const*)SD_Path, 0) != FR_OK)
    { /* FatFs Initialization Error */
      Error_Handler();
    } else
    {// if(f_mkfs((TCHAR const*)SD_Path, 0, 0) != FR_OK) //Format SD memory card// {// /* FatFs Format Error */// Error_Handler();// }
    } /* USER CODE END Init */}12345678910111213141516171819202122232425261234567891011121314151617181920212223242526

As shown in the above code, define the global variable SDFatFs for subsequent code. 
The commented out f_mkfs line after mounting the SD card in the above code is to format the SD card. You can decide whether to format the SD card according to the situation. Here, choose not to format it.

3.3 File system and SDIO connection part

Some parts of the file system and SDIO need to be modified. 
Open the bsp_driver_sd.c file and find the BSP_SD_IsDetected function. Since the SD card insertion detection is implemented through the user-defined pin (in this case, it is detected through PH13), it is necessary to match it here. Add your own code between /* USER CODE BEGIN 1 / and / USER CODE END 1 */ in this function:

uint8_t BSP_SD_IsDetected(void)
{
  __IO uint8_t status = SD_PRESENT; /* USER CODE BEGIN 1 */
  /* user code can be inserted here */
  if(HAL_GPIO_ReadPin(SD_DETECT_GPIO_Port, SD_DETECT_Pin) != GPIO_PIN_RESET) //Low level when SD card is inserted
    {
        status =SD_NOT_PRESENT;
    } /* USER CODE END 1 */     

  return status;
}123456789101112131415123456789101112131415

That's it, the transplant is done, the next step is to write the test code.

3.4 Testing the File System

Go back to the main function and add your own file system test code between /* USER CODE BEGIN 2 / and / USER CODE END 2 */ as follows:

if(f_open(&MyFile, "STM32.TXT", FA_CREATE_ALWAYS | FA_WRITE) != FR_OK) //Create a file
    { /* 'STM32.TXT' file Open for write Error */
        Error_Handler();
    } else
  {
            res = f_write(&MyFile, wtext, sizeof(wtext), (void *)&byteswritten); //Write content
            if((byteswritten == 0) || (res != FR_OK))
            { /* 'STM32.TXT' file Write or EOF Error */
                Error_Handler();
            } else
            {
                f_close(&MyFile); //Close the file

                /*##-7- Open the text file object with read access ###############*/
                if(f_open(&MyFile, "STM32.TXT", FA_READ) != FR_OK) //Open the file again
                { /* 'STM32.TXT' file Open for read Error */
                    Error_Handler();
                } else
                {
                    res = f_read(&MyFile, rtext, sizeof(rtext), (UINT*)&bytesread); //Read content

                    if((bytesread == 0) || (res != FR_OK))
                    { /* 'STM32.TXT' file Read or EOF Error */
                        Error_Handler();
                    } else
                    {
                        f_close(&MyFile); //Close the file

                /*##-10- Compare read data with the expected data ############*/
                if((bytesread != byteswritten)) //Compare
                { /* Read data is different from the expected data */
                  Error_Handler();
                } else
                { /* Success of the demo: no error occurrence */
                  HAL_GPIO_WritePin(LED1_GPIO_Port,LED1_Pin,GPIO_PIN_SET);
                }
                    }
                }
            }
  }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051521234567891011121314151617 1819202122232425262728293031323334353637383940414243444546474849505152

The above code flow is: create a file, write content, close the file, then open the file again, read the content, close the file, and finally compare whether the read content is the written content, and process it according to the comparison result.

Finally, compile the entire project and burn it to the STM3240G-EVAL evaluation board for testing. The running result is OK.

4 Conclusion

CubeMx is quite powerful. It can automatically generate a project by setting up a file system of an SD memory card in a few steps. You only need to modify a few key places to complete such a seemingly complex project in a few simple steps. CubeMx is a very powerful tool. The most critical parameter in this article is the stack size set to 0x800. People who have never encountered this problem will take a long time to discover this problem, so I emphasize it again.

Finally, the code project download link address is attached: 
http://download.csdn.net/detail/flydream0/9649702


Keywords:CubeMx Reference address:How to use CubeMx to create a file system project based on SD card

Previous article:Why does the STM32F0xx APP need to remap SRAM in the main function after adding IAP?
Next article:Low power consumption test of STM32L152

Latest Microcontroller Articles
  • Download from the Internet--ARM Getting Started Notes
    A brief introduction: From today on, the ARM notebook of the rookie is open, and it can be regarded as a place to store these notes. Why publish it? Maybe you are interested in it. In fact, the reason for these notes is ...
  • Learn ARM development(22)
    Turning off and on interrupts Interrupts are an efficient dialogue mechanism, but sometimes you don't want to interrupt the program while it is running. For example, when you are printing something, the program suddenly interrupts and another ...
  • Learn ARM development(21)
    First, declare the task pointer, because it will be used later. Task pointer volatile TASK_TCB* volatile g_pCurrentTask = NULL;volatile TASK_TCB* vol ...
  • Learn ARM development(20)
    With the previous Tick interrupt, the basic task switching conditions are ready. However, this "easterly" is also difficult to understand. Only through continuous practice can we understand it. ...
  • Learn ARM development(19)
    After many days of hard work, I finally got the interrupt working. But in order to allow RTOS to use timer interrupts, what kind of interrupts can be implemented in S3C44B0? There are two methods in S3C44B0. ...
  • Learn ARM development(14)
  • Learn ARM development(15)
  • Learn ARM development(16)
  • Learn ARM development(17)
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号