STM32CubeMX

Table Of Contents

- STM32CubeMX documentation
- CubeMX User Manual
  - 1 STM32Cube overview
  - 2 Getting started with STM32CubeMX
  - 3 Installing and running STM32CubeMX
  - 4 STM32CubeMX user interface
  - 5 STM32CubeMX tools
  - 6 STM32CubeMX C Code generation overview
  - 7 Code generation for dual-core MCUs (STM32H7 dual-core product lines only)
  - 8 Code generation with TrustZone enabled (STM32L5 series only)
  - 9 Device tree generation (STM32MPUs only)
  - 10 Support of additional software components using CMSIS-Pack standard
  - 11 Tutorial 1: From pinout to project C code generation using an MCU of the STM32F4 series
  - 12 Tutorial 2 - Example of FatFs on an SD card using STM32429I-EVAL evaluation board
  - 13 Tutorial 3 - Using the Power Consumption Calculator to optimize the embedded application consumption and more
  - 14 Tutorial 4 - Example of UART communications with an STM32L053xx Nucleo board
  - 15 Tutorial 5: Exporting current project configuration to a compatible MCU
  - 16 Tutorial 6 - Adding embedded software packs to user projects
  - 17 Tutorial 7 - Using the X-Cube-BLE1 software pack
  - 18 Creating LPBAM projects
  - Appendix A STM32CubeMX pin assignment rules
  - Appendix B STM32CubeMX C code generation design choices and limitations
  - Appendix C STM32 microcontrollers power consumption parameters
  - Appendix D STM32Cube embedded software packages
  - Revision history
- Release Notes
  - Release details
  - Release fixes
  - Known limitations
    - Miscellaneous
    - 2.1. When selecting microcontrollers in the STM32C0 series
    - 2.2. When selecting microcontrollers in the STM32G0 series
    - 2.3. When selecting microcontrollers in the STM32G4 series
    - 2.4. When selecting microcontrollers in the STM32H5 series
    - 2.5. When selecting microcontrollers in the STM32H7 series
    - 2.6. When selecting dual-core microcontrollers in the STM32H7 series
    - 2.7. When selecting microcontrollers in the STM32L5 series
    - 3.4. How to improve the wake-up from Stop sequences without relying on the global SystemClock_Config()
    - 3.3. List pinout-compatible microcontrollers
    - 3.2. DDR binaries for the STM32MP1 boards
    - 3.1. Command line authentication required
    - 2.21. Symbolic links on Ubuntu
    - 2.20. User manual
    - 2.19. DDR test suite
    - 2.18. STM32CubeIDE toolchain
    - 2.13. When selecting microcontrollers in the STM32WL series
    - 2.11. When selecting microcontrollers in the STM32WB series
    - 2.17. When using additional software packs
    - 2.16. When using the Example Selector
    - 2.15. When using the Memory Management Tool
    - 2.14. When selecting microprocessors in the STM32MP1 series
    - 2.11.1. When selecting microcontrollers in the STM32WB0 product lines
    - 2.12. When selecting microcontrollers in the STM32WBA series
    - 2.13.1. When selecting microcontrollers in the STM32WL33 product lines
    - 2.10. When selecting microcontrollers in the STM32U5 series
    - 2.9. When selecting microcontrollers in the STM32U3 series
    - 2.8. When selecting microcontrollers in the STM32N6 series
- Running STM32CubeMX in command-line mode
- FAQ
- Community

# 9 Device tree generation (STM32MPUs only)

STM32L552CETX_RAM | | – .sct (MDK-ARM), or | | | | | | | | – .ld (GCC compiler toolchains) | +—————————————+———————–+———————————————————————————————————————————————+

> Device tree generation (STM32MPUs only)

> 9 Device tree generation (STM32MPUs only)

> The Device tree in Linux is used to provide a way to describe non-discoverable hardware. STMicroelectronics is widely using the device tree for all the platform configuration data, including DDR configuration.

> Linux developers can manually edit device tree source files (dts), but as an alternative STM32CubeMX offers a partial device-tree generation service to reduce effort and to ease new comers. STM32CubeMX intends to generate partially device trees corresponding to board level configuration. Partial means that the entire (board level) device-trees are not generated, but only main sections that usually imply huge efforts and can cause compilation errors and dysfunction:

> • folders structure and files to folders distribution

> • dtsi and headers inclusions

> • pinCtrl and clocks generation

> • System-On-Chip device nodes positioning

> • multi-core related configurations (Etzpc binding, resources manager binding, peripherals assignment)

> 9.1 Device tree overview

> To run properly, any piece of software needs to get the hardware description of the platform on which it is executed, including the kind of CPU, the memory size and the pin configuration. OpenSTLinux firmware has put such non-discoverable hardware description in a separate binary, the device tree blob (dtb). The device tree blob is compiled from the device tree source files (dts) using the dtc compiler provided with the OpenSTLinux distribution.

> The device tree structure consist of a board level file (.dts) that includes two device tree source include files (.dtsi): a soc level file and a –pinctrl file, that lists the pin muxing configurations.

> The device tree structure is very close to C language multiple level structures with the “root” (/) being the highest level then “peripherals” being sub-nodes described further in the hierarchy (see figures 584, 585 and 586).

> STM32CubeMX generation uses widely overloading mechanisms to complete or change some SOC devices definitions when user configurations require it.

> Device tree generation (STM32MPUs only)

> Figure 584. STM32CubeMX generated DTS – Extract 1

> Figure 585. STM32CubeMX generated DTS – Extract 2

> Device tree generation (STM32MPUs only)

> Figure 586. STM32CubeMX generated DTS – Extract 3

> For more details refer to “Device Tree for Dummies” from Thomas Petazzoni, available on https://elinux.org.

> For more information about STM32MPUs device tree specificities, refer to ST Wiki https://wiki.st.com/stm32mpu.

> 9.2 STM32CubeMX Device tree generation

> For STM32MPUs, STM32CubeMX code generation feature has been extended to generate Device trees (DT) configuring the firmware.

> DTS generation is accessible through the same button.

> Device tree generation (STM32MPUs only)

> The DT generation path can be configured from the Project Manager view, in the Advanced

> Settings tab, under OpenSTLinux Settings (see Figure 587). For each Device tree STM32CubeMX generates Device tree source (DTS) files.

> Figure 587. Project settings to configure Device tree path

> The Device tree structure consists of:

> • a complete clock-tree

> • a complete pin control

> • a complete multi-cores references definition

> • a set of device nodes and sub-nodes

> • user sections that can be filled to have complete and bootable Device trees (contents are not lost at next generation).

> The generated DTS files reflect the user configuration, such as the assignment of peripherals to runtime contexts and boot loaders, or clock tree settings.

> STM32CubeMX DT generation ensures the coherency between the different DTs.

> Additionally, it generates the DDR configuration file as part of the boot loader Device trees.

> These files, along with the files they include, are compiled to create the device tree blob for the targeted firmware.

> The STM32CubeMX Device tree structure depends upon the targeted firmware and, in a few cases, upon the OpenSTLinux manifest version and/or the MPU family. The structures are detailed in https://wiki.st.com/stm32mpu/wiki/Category:Platform_configuration.

> The device tree nodes generated by STM32CubeMX can be completed by filling the user sections following the device tree bindings of the different firmware.

> Note: To continue the process and learn how to use the generated files, see the dedicated Wiki pages for MPUs.

> Support of additional software components using CMSIS-Pack standard

> 10 Support of additional software components using

> CMSIS-Pack standard

> The CMSIS-Pack standard describes a delivery mechanism for software components, device parameters, and evaluation board support.

> The XML-based package description (pdsc) file describes the content of a software pack (file collection). It includes source code, header files, software libraries, documentation and source code templates. A software pack consists of the complete file collection along with the pdsc file, shipped in ZIP-format. After installing a software pack, all the included software components are available to the development tools.

> A software component is a collection of source modules, header and configuration files as well as libraries. Packs containing software components can also include example projects and user code templates.

> Refer to http://www.keil.com website for more details.

> STM32CubeMX supports third-party and other STMicroelectronics embedded software solutions, delivered as software packs. STM32CubeMX enables to:

> 1. Install software packs and check for updates (see Section 3.4.5).

> 2. Select software components for the current project (see Section 4.15). Once this is done, the selected components appear in the tree view (see Figure 588).

> 3. Enable the software component from the tree view (see Figure 589). Use contextual help to get more details on the selection.

> 4. Configure software components (see Figure 589). This function is possible only for components coming with files in STM32CubeMX proprietary format.

> 5. Generate the C project for selected toolchains (see Figure 590).

> a) Software components files are automatically copied to the project.

> b) Software component configuration and initialization code are automatically generated. This function is possible only for components coming with files in STM32CubeMX proprietary format.

> Support of additional software components using CMSIS-Pack standard

> Figure 588. Selecting a CMSIS-Pack software component

> Figure 589. Enabling and configuring a CMSIS-Pack software component

> Support of additional software components using CMSIS-Pack standard

> Figure 590. Project generated with CMSIS-Pack software component

11 Tutorial 1: From pinout to project C code generation

using an MCU of the STM32F4 series

This section describes the configuration and C code generation process. It takes as an example a simple LED toggling application running on the STM32F4DISCOVERY board.

11.1 Creating a new STM32CubeMX project

1. Select File > New project from the main menu bar or New project from the Home page.

2. Select the MCU/MPU Selector tab and filter down the STM32 portfolio by selecting STM32F4 as ‘Series’, STM32F407 as ‘Lines’, and LQFP100 as ‘Package’ (see Figure 591).

3. Select the STM32F407VGTx from the MCU list and click OK.

Figure 591. MCU selection

STM32CubeMX views are then populated with the selected MCU database ( Figure 592). Optionally, remove the MCUs Selection bottom window by deselecting Window > Outputs submenu (see Figure 593).

11.2 Configuring the MCU pinout

For a detailed description of menus, advanced actions and conflict resolutions, refer to Section 4 and Appendix A.

1. By default, STM32CubeMX shows the Pinout view.

2. By default, is unchecked, allowing STM32CubeMX to

move the peripheral functions around and to find the optimal pin allocation (the one that accommodates the maximum number of peripheral modes).

Since the MCU pin configurations must match the STM32F4DISCOVERY board,

enable for STM32CubeMX to maintain the peripheral

function allocation (mapping) to a given pin. This setting is saved as a user preference, to be restored when reopening the tool or when loading another project.

3. Select the required peripherals and peripheral modes:

a) Configure the GPIO to output the signal on the STM32F4DISCOVERY green LED by right-clicking PD12 from the Pinout view, then select GPIO_output:

Figure 594. GPIO pin configuration

b) Enable a timer to be used as timebase for toggling the LED. This is done by selecting Internal Clock as TIM3 clock source from the peripheral tree (see Figure 595).

c) You can also configure the RCC to use an external oscillator as clock source (see Figure 596).

This completes the pinout configuration for this example.

Note: Starting with STM32CubeMX 4.2, the user can skip the pinout configuration by directly loading ST Discovery board configuration from the Board selector tab.

When saving for the first time, select a destination folder and filename for the project. The .ioc extension is added automatically to indicate that this is an STM32CubeMX configuration file.

|image528|

11.4 Generating the report

Reports can be generated at any time during the configuration:

> 1. Click to generate .pdf and .txt reports.

If a project file has not been created yet, a warning prompts the user to save the project first and requests a project name and a destination folder (see Figure 598). An .ioc file is then generated for the project along with a .pdf and .txt reports with the same name.

Figure 598. Generate Project Report - New project creation

|image529|

Answering No will require to provide a name and location for the report only.

As shown in Figure 599, a confirmation message is displayed when the operation is successful.

Figure 599. Generate Project Report - Project successfully created

|image530|

2. Open the .pdf report using Adobe Reader or the .txt report using your favorite text editor. The reports summarize all the settings and MCU configuration performed for the project.

11.5 Configuring the MCU clock tree

The following sequence describes how to configure the clocks required by the application based on an STM32F4 MCU.

STM32CubeMX automatically generates the system, CPU and AHB/APB bus frequencies from the clock sources and prescalers selected by the user. Wrong settings are detected and highlighted in fuchsia through a dynamic validation of minimum and maximum conditions. Useful tooltips provide a detailed description of the actions to undertake when the settings are unavailable or wrong. User frequency selection can influence some peripheral parameters (e.g. UART baud rate limitation).

STM32CubeMX uses the clock settings defined in the Clock tree view to generate the initialization C code for each peripheral clock. Clock settings are performed in the generated C code as part of RCC initialization within the project main.c and in stm32f4xx_hal_conf.h (HSE, HSI and external clock values expressed in Hertz).

Follow the sequence below to configure the MCU clock tree:

1. Click the Clock Configuration tab to display the clock tree (see Figure 600).

The internal (HSI, LSI), system (SYSCLK) and peripheral clock frequency fields cannot be edited. The system and peripheral clocks can be adjusted by selecting a clock source, and optionally by using the PLL, prescalers and multipliers.

Figure 600. Clock tree view

|image531|

2. Select the clock source (HSE, HSI or PLLCLK) that will drive the system clock.

In the example taken for the tutorial, select HSI to use the internal 16 MHz clock (see Figure 601).

|image532|

To use an external clock source (HSE or LSE), the RCC peripheral must be configured in the Pinout view, as pins will be used to connect the external clock crystals (see Figure 602).

|image533|

Other clock configuration options for the STM32F4DISCOVERY board:

– Select the external HSE source and enter 8 in the HSE input frequency box since an 8 MHz crystal is connected on the discovery board:

Figure 603. HSE clock source enabled

|image534|

– Select the external PLL clock source and the HSI or HSE as the PLL input clock source.

Figure 604. External PLL clock source enabled

|image535|

3. Keep the core and peripheral clocks to 16 MHz using HSI, no PLL and no prescaling.

Note: Optionally, further adjust the system and peripheral clocks using PLL, prescalers and multipliers:

Other clock sources independent from the system clock can be configured as follows:

– USB OTG FS, RNG and SDIO clocks are driven by an independent PLL output.

– I2S peripherals come with their own internal clock (PLLI2S), alternatively derived by an independent external clock source.

– USB OTG HS and Ethernet clocks are derived from an external source.

4. Optionally, configure the prescaler for the Microcontroller Clock Output (MCO) pins that allow to output two clocks to the external circuit.

5. Click to save the project.

6. Go to the Configuration tab to proceed with the project configuration.

11.6 Configuring the MCU initialization parameters

** Caution: ** The C code generated by STM32CubeMX covers the initialization of the MCU peripherals and middlewares using the STM32Cube firmware libraries.

11.6.1 Initial conditions

From the Pinout & Configuration tab, select and configure (one by one) every component (peripheral, middleware, additional software) required by the application using the Mode and Configuration panels (see Figure 605).

Tooltips and warning messages are displayed when peripherals are not properly configured (see Section 4 for details).

Note: The RCC peripheral initialization uses the parameter configuration done in this view as well as the configuration done in the Clock tree view (clock source, frequencies, prescaler values).

Figure 605. Pinout & Configuration view

|image536|

Each peripheral instance corresponds to a dedicated button in the main panel. Some peripheral modes have no configurable parameters, as illustrated below.

Figure 606. Case of Peripheral and Middleware without configuration parameters

|image537|

Follow the steps below to proceed with peripheral configuration:

1. Click the peripheral button to open the corresponding configuration window.

In our example

a) click TIM3 to open the timer configuration window.

Figure 607. Timer 3 configuration window

|image538|

b) with a 16 MHz APB clock (Clock tree view), set the prescaler to 16000 and the counter period to 1000 to make the LED blink every millisecond.

Figure 608. Timer 3 configuration

|image539|

2. Optionally, and when available, select:

– The NVIC Settings tab to display the NVIC configuration and enable interruptions for this peripheral.

– The DMA Settings tab to display the DMA configuration and to configure DMA transfers for this peripheral.

In the tutorial example, the DMA is not used and the GPIO settings remain unchanged. The interrupt is enabled, as shown in Figure 609.

– The GPIO Settings tab to display the GPIO configuration and to configure the GPIOs for this peripheral.

– Insert an item:

– The User Constants tab to specify constants to be used in the project.

Figure 609. Enabling Timer 3 interrupt

|image540|

The user can adjust all pin configurations from this window. A small icon along with a tooltip indicates the configuration status.

Figure 610. GPIO configuration color scheme and tooltip

|image541|

Follow the sequence below to configure the GPIOs:

1. Click the GPIO button in the Configuration view to open the Pin Configuration window.

2. The first tab shows pins that have been assigned a GPIO mode, but not for a dedicated peripheral and middleware. Select Pin Name to open the configuration for that pin.

In the tutorial example, select PD12 and configure it in output push-pull mode to drive the STM32F4DISCOVERY LED (see Figure 611).

|image542|

11.6.4 Configuring the DMAs

This is not required for this example. It is recommended to use DMA transfers to offload the CPU. The DMA Configuration window provides a fast and easy way to configure the DMAs (see Figure 612):

1. add a new DMA request and select among a list of possible configurations.

2. select among the available streams.

3. select the Direction: Memory to Peripheral or Peripheral to Memory.

4. select a Priority.

5. enable the FIFO.

Note: Configuring the DMA for a given peripheral and middleware can also be performed using the Peripheral and Middleware configuration window.

Figure 612. DMA parameters configuration window

|image543|

This is not required for the example taken for the tutorial.

If a peripheral is required for a middleware mode, the peripheral must be configured in the Pinout view for the middleware mode to become available. A tooltip can guide the user as shown below.

|image544|

> 1. Configure the USB peripheral from the Pinout view.

Figure 614. USB Host configuration

|image545|

2. Select MSC_FS class from USB Host middleware.

3. Select the checkbox to enable FatFs USB mode in the tree panel.

Figure 615. FatFs over USB mode enabled

|image546|

4. Select the Configuration view. FatFs and USB buttons are then displayed.

Figure 616. System view with FatFs and USB enabled

5. FatFs and USB using default settings are already marked as configured . Click FatFs and USB buttons to display default configuration settings. You can also change them by following the guidelines provided at the bottom of the window.

Figure 617. FatFs define statements

11.7 Generating a complete C project

11.7.1 Setting project options

Default project settings can be adjusted prior to C code generation as shown in Figure 618.

1. Select the Project Manager view to update project settings and generation options.

2. Select the Project Tab and choose a Project name, location, a toolchain and a toolchain version to generate the project (see Figure 618).

Figure 618. Project Settings and toolchain selection

> 3. Select the Code Generator tab to choose various C code generation options:

– The library files copied to Projects folder.

– C code regeneration (e.g. what is kept or backed up during C code regeneration).

– HAL specific action (for example, set all free pins as analog I/Os to reduce power consumption).

In the tutorial example, select the settings as displayed in Figure 619, and click OK.

Note: A dialog window appears when the firmware package is missing. Go to next section for explanation on how to download the firmware package.

Figure 619. Project Manager menu - Code Generator tab

During the generation, STM32CubeMX copies files from the relevant STM32Cube MCU package into the project folder so that the project can be compiled. When generating a project for the first time, the firmware package is not available on the user PC and a warning is displayed.

Figure 620. Warning message for missing firmware package

2. STM32CubeMX offers to download the relevant firmware package or to go on. Click Download to obtain a complete project, ready to use in the selected IDE.

By clicking Continue, only Inc and Src folders are created, holding STM32CubeMX generated initialization files. The necessary firmware and middleware libraries must be copied manually to obtain a complete project. If the download fails, an error message is displayed.

Figure 621. Error during download

To solve this issue, execute the next two steps. Skip them otherwise.

3. Select Help > Connection & Updates, a new window appears.

4. Go to the Connection Parameters tab and adjust the parameters to match your network configuration.

5. Click Check connection. The check mark turns green once the connection is established.

Figure 622. Updated settings with connection

|image553|

6. Once the connection is functional, click to generate the C code.

The progress is displayed (see next figures).

Figure 623. Downloading the firmware package

|image554|

7. Finally, a confirmation message is displayed to indicate that the C code generation has been successful.

Figure 625. C code generation completion message

|image555|

8. Click Open Folder to display the generated project contents or click Open Project to open the project directly in your IDE. Then proceed with Section 11.8.

Figure 626. C code generation output folder

|image556|

The generated project contains:

• The STM32CubeMX .ioc project file located in the root folder. It contains the project user configuration and settings generated through STM32CubeMX user interface.

• The Drivers and Middlewares folders hold copies of the firmware package files relevant for the user configuration.

• The Projects folder contains IDE specific folders with all the files required for the project development and debug within the IDE.

• The Inc and Src folders contain STM32CubeMX generated files for middleware, peripheral and GPIO initialization, including the main.c file. The STM32CubeMX generated files contain user-dedicated sections allowing to insert user-defined C code.

Caution: C code written within the user sections is preserved at next C code generation, while C code written outside these sections is overwritten.

User C code is lost if user sections are moved or if user sections delimiters are renamed.

STM32CubeMX includes a feature that allows users to pause and resume the download actions. This capability is particularly useful in scenarios where network connectivity is unstable or frequently interrupted. This also offers the ability to verify network issue, and connection speed.

The user does not need to restart large downloads from scratch after a brief Internet hiccup. To stop the download, click the Pause button.

Figure 627. Pause button

|image557|

Once the Pause button has been clicked, a temporary file is created under the path

~/STM32Cube/Repository, to keep the download context

Figure 628. Creating the .tmp file

|image558|

To restart the download, click the Resume button.

Figure 629. Resume button

|image559|

The button is grayed if the download has been completed, and the unzip of the downloaded folder is started.

Figure 630. Resume button during the unzipping of downloaded files

|image560|

When closing the download dialog box an additional window appears, prompting the user to decide whether to keep the temporary file:

• If the user clicks Yes, the system retains the temporary file to facilitate the download.

• If the user clicks No, the system deletes the temporary file.

Figure 631. Closing the download window without clicking the Resume button

|image561|

When the Cancel button is clicked, all procedures are canceled. The system stops the download and deletes the temporary file.

|image562|

11.8 Building and updating the C code project

This example explains how to use the generated initialization C code and complete the project, within IAR™ EWARM toolchain, to have the LED blink according to the TIM3 frequency.

A folder is available for the toolchains selected for C code generation: the project can be generated for more than one toolchain by choosing a different toolchain from the Project Manager menu and clicking Generate code once again.

1. Open the project directly in the IDE toolchain by clicking Open Project from the dialog window or by double-clicking the relevant IDE file available in the toolchain folder under STM32CubeMX generated project directory (see Figure 625).

Figure 633. C code generation output: Projects folder

|image563|

> 2. As an example, select .eww file to load the project in the IAR™ EWARM IDE.

Figure 634. C code generation for EWARM

> 3. Select the main.c file to open in editor.

Figure 635. STM32CubeMX generated project open in IAR™ IDE

The htim3 structure handler, system clock, GPIO and TIM3 initialization functions are defined. The initialization functions are called in the main.c. For now the user C code sections are empty.

4. In the IAR™ IDE, right-click the project name and select Options.

Figure 636. IAR™ options

5. Click the ST-LINK category and make sure SWD is selected to communicate with the STM32F4DISCOVERY board. Click OK.

6. Select Project > Rebuild all. Check if the project building has succeeded.

Figure 638. Project building log

7. Add user C code in the dedicated user sections only.

Note: The main while(1) loop is placed in a user section.

For example:

a) Edit the main.c file.

b) To start timer 3, update User Section 2 with the following C code:

Figure 639. User Section 2

c) Then, add the following C code in User Section 4:

Figure 640. User Section 4

This C code implements the weak callback function defined in the HAL timer driver (stm32f4xx_hal_tim.h) to toggle the GPIO pin driving the green LED when the timer counter period has elapsed.

8. Rebuild and program your board using . Make sure the SWD ST-LINK option is checked as a Project options otherwise board programming will fail.

9. Launch the program using . The green LED on the STM32F4DISCOVERY board will blink every second.

10. To change the MCU configuration, go back to STM32CubeMX user interface, implement the changes and regenerate the C code. The project will be updated,

preserving the C code in the user sections if option in

Project Manager’s Code Generator tab is enabled.

11.9 Switching to another MCU

STM32CubeMX allows loading a project configuration on an MCU of the same series.

Proceed as follows:

1. Select File > New Project.

2. Select an MCU belonging to the same series. As an example, you can select the STM32F429ZITx that is the core MCU of the 32F429IDISCOVERY board.

3. Select File > Import project. In the Import project window, browse to the .ioc file to load. A message warns you that the currently selected MCU (STM32F429ZITx) differs from the one specified in the .ioc file (STM32F407VGTx). Several import options are proposed (see Figure 641).

4. Click the Try Impor t button and check the import status to verify if the import has been successful.

5. Click OK to really import the project. An output tab is then displayed to report the import results.

6. The green LED on 32F429IDISCOVERY board is connected to PG13: CTRL+ right click PD12 and drag and drop it on PG13.

7. From Project Manager project tab configure the new project name and folder location. Click Generate icon to save the project and generate the code.

8. Select Open the project from the dialog window, update the user sections with the user code, making sure to update the GPIO settings for PG13. Build the project and flash the board. Launch the program and check that LED blinks once per second.

Figure 641. Import Project menu

12 Tutorial 2 - Example of FatFs on an SD card using

STM32429I-EVAL evaluation board

The tutorial consists in creating and writing to a file on the STM32429I-EVAL1 SD card using the FatFs file system middleware.

To generate a project and run tutorial 2, follow the sequence below:

1. Launch STM32CubeMX.

2. Select File > New Project. The Project window opens.

3. Click the Board Selector Tab to display the list of ST boards.

4. Select EvalBoard as type of Board and STM32F4 as Series to filter down the list.

5. Answer Yes to Initialize all peripherals with their default mode so that the code is generated only for the peripherals used by the application.

6. Select the STM32429I-EVAL board and click OK. Answer No in the dialog box asking to initialize all peripherals to their default modes (see Figure 642). The Pinout view is loaded, matching the MCU pinout configuration on the evaluation board (see Figure 643).

Figure 642. Board peripheral initialization dialog box

Figure 643. Board selection

7. From the Peripheral tree on the left, expand the SDIO peripheral and select “SD 4 bits wide bus” (see Figure 644). In the configuration panel, from the DMA settings tab, add SDIO_RX and SDIO_TX DMA requests.

8. Finally, go pack to the peripheral tree panel, select NVIC and enable the SDIO global interrupt from the configuration panel.

9. Under the Middlewares category, check SD card as FatFs mode (see Figure 645).

Figure 645. FatFs mode configuration

From the Pinout view on the right, enable, as GPIO input, a pin to be used for the SDIO detection.

In the configuration panel below the mode panel, go to the platform settings tab and configure the SD_detection using the pin previously enabled.

Finally, go to FatFs “Advanced settings tab” and enable “Use DMA template”.

10. Configure the clocks as follows:

a) Select the RCC peripheral from the Pinout view (see Figure 646).

Figure 646. RCC peripheral configuration

b) Configure the clock tree from the clock tab (see Figure 647).

Figure 647. Clock tree view

11. In the Project tab, specify the project name and destination folder. Then, select the EWARM IDE toolchain.

Note that project heap and stack size can be adjusted to the minimum required for the FATFS application.

Figure 648. FATFS tutorial - Project settings

12. Click Ok. Then, on the toolbar menu, click

13. Upon code generation completion, click Open Project in the Code Generation dialog window (see Figure 649). This opens the project directly in the IDE.

Figure 649. C code generation completion message

14. In the IDE, check that heap and stack sizes are sufficient: right click the project name and select Options, then select Linker. Check Override default to use the icf file from STM32CubeMX generated project folder. if not already done through STM32CubeMX User interface (under Linker Settings from Project Manager’s project tab), adjust the heap and stack sizes (see Figure 650).

Note: When using the MDK-Arm toolchain, go to the Application/MDK-ARM folder and double-click the startup_xx.s file to edit and adjust the heap and stack sizes there.

15. Go to the Application/User folder. Double-click the main.c file and edit it.

16. The tutorial consists in creating and writing to a file on the evaluation board SD card using the FatFs file system middleware: a) At startup all LEDs are OFF.

b) The red LED is turned ON to indicate that an error occurred (e.g. FatFs initialization, file read/write access errors).

c) The orange LED is turned ON to indicate that the FatFs link has been successfully mounted on the SD driver.

d) The blue LED is turned ON to indicate that the file has been successfully written to the SD card.

e) The green LED is turned ON to indicate that the file has been successfully read from file the SD card.

17. For use case implementation, update main.c with the following code:

a) Insert main.c private variables in a dedicated user code section:

/* USER CODE BEGIN PV */

/* Private variables ——————————————*/

FATFS SDFatFs; /* File system object for SD card logical drive */ FIL MyFile; /* File object */ const char wtext[] = “Hello World!”; static uint8_t buffer[_MAX_SS]; /* a work buffer for the f_mkfs() */

/* USER CODE END PV */

b) Insert main functional local variables:

int main(void) {

> /* USER CODE BEGIN 1 */

> FRESULT res; /* FatFs function common result code */ uint32_t byteswritten, bytesread; /* File write/read counts */ char rtext[256]; /* File read buffer */

> /* USER CODE END 1 */

> /* MCU Configuration—————————————-*/

> /* Reset of all peripherals, Initializes the Flash interface and the

Systick. */

HAL_Init();

3. Insert user code in the main function, after initialization calls and before the while loop, to perform actual read/write from/to the SD card:

int main(void)

{

….

MX_FATFS_Init();

> /* USER CODE BEGIN 2 */

/*##-0- Turn all LEDs off(red, green, orange and blue) */

> HAL_GPIO_WritePin(GPIOG, (GPIO_PIN_10 | GPIO_PIN_6 | GPIO_PIN_7 |

GPIO_PIN_12), GPIO_PIN_SET);

/*##-1- FatFS: Link the SD disk I/O driver ##########*/

> if(retSD == 0){

/* success: set the orange LED on */

> HAL_GPIO_WritePin(GPIOG, GPIO_PIN_7, GPIO_PIN_RESET); /*##-2- Register the file system object to the FatFs module ###*/ if(f_mount(&SDFatFs, (TCHAR const*)SDPath, 0) != FR_OK){ /* FatFs Initialization Error : set the red LED on */ HAL_GPIO_WritePin(GPIOG, GPIO_PIN_10, GPIO_PIN_RESET); while(1);

> } 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, FM_ANY, 0, buffer, sizeof(buffer))

!= FR_OK){

> /* FatFs Format Error : set the red LED on */ HAL_GPIO_WritePin(GPIOG, GPIO_PIN_10, GPIO_PIN_RESET); while(1);

> } else {

/*##-4- Create & Open a new text file object with write access#*/ if(f_open(&MyFile, “Hello.txt”, FA_CREATE_ALWAYS | FA_WRITE) !=

FR_OK){

> /* ‘Hello.txt’ file Open for write Error : set the red LED on */ HAL_GPIO_WritePin(GPIOG, GPIO_PIN_10, GPIO_PIN_RESET); while(1);

> } else {

/*##-5- Write data to the text file ####################*/ res = f_write(&MyFile, wtext, sizeof(wtext), (void

*)&byteswritten); if((byteswritten == 0) || (res != FR_OK)){

> /* ‘Hello.txt’ file Write or EOF Error : set the red LED on */ HAL_GPIO_WritePin(GPIOG, GPIO_PIN_10, GPIO_PIN_RESET); while(1);

> } else {

/*##-6- Successful open/write : set the blue LED on */ HAL_GPIO_WritePin(GPIOG, GPIO_PIN_12, GPIO_PIN_RESET); f_close(&MyFile);

/*##-7- Open the text file object with read access #*/ if(f_open(&MyFile, “Hello.txt”, FA_READ) != FR_OK){

> /* ‘Hello.txt’ file Open for read Error : set the red LED on */ HAL_GPIO_WritePin(GPIOG, GPIO_PIN_10, GPIO_PIN_RESET); while(1);

> } else {

/*##-8- Read data from the text file #########*/ res = f_read(&MyFile, rtext, sizeof(wtext), &bytesread); if((byteswritten == 0)|| (res != FR_OK)){

> /* ‘Hello.txt’ file Read or EOF Error : set the red LED on */ HAL_GPIO_WritePin(GPIOG, GPIO_PIN_10, GPIO_PIN_RESET); while(1);

> } else {

> /* Successful read : set the green LED On */

> HAL_GPIO_WritePin(GPIOG, GPIO_PIN_6, GPIO_PIN_RESET);

/*##-9- Close the open text file ################*/ f_close(&MyFile);

/*##-10- Unlink the micro SD disk I/O driver #########*/

> FATFS_UnLinkDriver(SDPath);