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

# 6 STM32CubeMX C Code generation overview

6.1 STM32Cube code generation using only HAL drivers

> (default mode)

> During the C code generation process, STM32CubeMX performs the following actions:

> 1. If it is missing, it downloads the relevant STM32Cube MCU package from the user repository. STM32CubeMX repository folder is specified in the Help > Updater settings menu.

> 2. It copies from the firmware package, the relevant files in Drivers/CMSIS and Drivers/STM32F4_HAL_Driver folders and in the Middleware folder if a middleware was selected.

> 3. It generates the initialization C code ( .c/.h files) corresponding to the user MCU configuration and stores it in the Inc and Src folders. By default, the following files are included:

> – stm32f4xx_hal_conf.h file: this file defines the enabled HAL modules and sets some parameters (e.g. External High Speed oscillator frequency) to predefined default values or according to user configuration (clock tree).

> – stm32f4xx_hal_msp.c (MSP = MCU Support package): this file defines all initialization functions to configure the peripheral instances according to the user configuration (pin allocation, enabling of clock, use of DMA and Interrupts).

> – main.c is in charge of:

> Resetting the MCU to a known state by calling the HAL_init() function that resets all peripherals, initializes the flash memory interface and the SysTick.

> Configuring and initializing the system clock.

> Configuring and initializing the GPIOs that are not used by peripherals.

> Defining and calling, for each configured peripheral, a peripheral initialization function that defines a handle structure that will be passed to the corresponding peripheral HAL init function which in turn will call the peripheral HAL MSP initialization function. Note that when LwIP (respectively USB) middleware is used, the initialization C code for the underlying Ethernet (respectively USB peripheral) is moved from main.c to LwIP (respectively USB) initialization C code itself.

> – main.h file:

> This file contains the define statements corresponding to the pin labels set from

> the Pinout tab, as well as the user project constants added from the Configuration tab (refer to Figure 564 and Figure 565 for examples):

> > #define MyTimeOut 10

> #define LD4_Pin GPIO_PIN_12 #define LD4_GPIO_Port GPIOD

> > #define LD3_Pin GPIO_PIN_13

> > #define LD3_GPIO_Port GPIOD

> > #define LD5_Pin GPIO_PIN_14

> #define LD5_GPIO_Port GPIOD

> > #define LD6_Pin GPIO_PIN_15

> #define LD6_GPIO_Port GPIOD

> Figure 564. Labels for pins generating define statements

> In case of duplicate labels, a unique suffix, consisting of the pin port letter and the pin index number, is added and used for the generation of the associated define statements.

> In the example of a duplicate I2C1 labels shown in Figure 566, the code generation produces the following code, keeping the I2C1 label on the original port B pin 6 define statements and adding B7 suffix on pin 7 define statements:

> > #define I2C1_Pin GPIO_PIN_6

> > #define I2C1_GPIO_Port GPIOB

> > #define I2C1B7_Pin GPIO_PIN_7

> #define I2C1B7_GPIO_Port GPIOB

> Figure 566. Duplicate labels

> In order for the generated project to compile, define statements shall follow strict naming conventions. They shall start with a letter or an underscore as well as the corresponding label. In addition, they shall not include any special character such as minus sign, parenthesis or brackets. Any special character within the label is replaced by an underscore in the define name.

> If the label contains character strings between “[]” or “()”, only the first string listed

> is used for the define name. As an example, the label “ LD6 [Blue Led]” corresponds the following define statements:

> #define LD6_Pin GPIO_PIN_15

> #define LD6_GPIO_Port GPIOD

> The define statements are used to configure the GPIOs in the generated initialization code. In the following example, the initialization of the pins labeled

> Audio_RST_Pin and LD4_Pin is done using the corresponding define statements:

> /*Configure GPIO pins : LD4_Pin Audio_RST_Pin */

> GPIO_InitStruct.Pin = LD4_Pin | Audio_RST_Pin;

> GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;

> GPIO_InitStruct.Pull = GPIO_NOPULL;

> GPIO_InitStruct.Speed = GPIO_SPEED_LOW;

> HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);

> 4. Finally it generates a Projects folder that contains the toolchain specific files that match the user project settings. Double-clicking the IDE specific project file launches the IDE and loads the project ready to be edited, built and debugged.

> 6.2 STM32Cube code generation using Low Layer drivers

> STM32CubeMX allows the user to generate peripheral initialization code based either on the peripheral HAL driver or on the peripheral Low Layer (LL) driver.

> The choice is made through the Project Manager view (see Section 4.11.3: Advanced Settings tab).

> The LL drivers are available only for the peripherals which require an optimized access and do not have a complex software configuration. The LL services allow performing atomic operations by changing the relevant peripheral registers content:

> • Examples of supported peripherals: RCC, ADC, GPIO, I2C, SPI, TIM, USART,… • Examples of peripherals not supported by LL drivers: USB, SDMMC, FSMC.

> The LL drivers are available within the STM32CubeL4 package:

> • They are located next to the HAL drivers ( stm32l4_hal_<peripheral_name>) within the Inc and Src directory of the

> STM32Cube_FW_L4_V1.6\Drivers\STM32L4xx_HAL_Driver folder. - They can be easily recognizable by their naming convention:

> stm32l4_ll_<peripheral_name>

> For more details on HAL and LL drivers refer to the STM32L4 HAL and Low-layer drivers user manual (UM1884).

> As the decision to use LL or HAL drivers is made on a peripheral basis, the user can mix both HAL and LL drivers within the same project.

> The following tables show the main differences between the three possible STM32CubeMX project generation options: HAL-only, LL-only, and mix of HAL and LL code.

> Table 24. LL versus HAL code generation: drivers included in STM32CubeMX projects

> Project configuration and drivers to be included | HAL only | LL only | Mix of HAL and LL | Comments
> CMSIS | Yes | Yes | Yes |
> STM32xxx_HAL_Driver | Only HAL driver files | Only LL driver files | Mix of HAL and LL driver files | Only the driver files required for a given configuration (selection of peripherals) are copied when the project settings option is set to “Copy only the necessary files”. Otherwise (“all used libraries” option) the complete set of driver files is copied.

> Table 25. LL versus HAL code generation: STM32CubeMX generated header files

> Generated header files | HAL only | LL only | Mix of HAL and LL | Comments
> main.h | Yes | Yes | Yes | This file contains the include statements and the generated define statements for user constants (GPIO labels and user constants).
> stm32xxx_hal_conf.h | Yes | No | Yes | This file enables the HAL modules necessary to the project.
> stm32xxx_it.h | Yes | Yes | Yes | Header file for interrupt handlers
> stm32xx_assert.h | No | Yes | Yes | This file contains the assert macros and the functions used for checking function parameters.

> Table 26. LL versus HAL: STM32CubeMX generated source files

> Generated source files | HAL only | LL only | Mix of HAL and LL | Comments
> main.c | Yes | Yes | Yes | Contains the main functions and, optionally, STM32CubeMX generated functions.
> stm32xxx_hal_msp.c | Yes | No | Yes | Contains the following functions: – HAL_MspInit – for peripherals using HAL drivers: HAL_<Peripheral>_MspInit, HAL_<Peripheral>_MspDeInit, These functions are available only for the peripherals that use HAL drivers.
> stm32xxx_it.c | Yes | Yes | Yes | Source file for interrupt handlers

> Table 27. LL versus HAL: STM32CubeMX generated functions and function calls
> Generated source files | HAL only | LL only | Mix of HAL and LL | Comments
> --- | --- | --- | --- | ---
> HAL_init() | Called in main.c | Not used | Called in main.c | This file performs the following functions: Configuration of flash memory prefetch and instruction and data caches Selection of the SysTick timer as timebase source Setting of NVIC group priority MCU low-level initialization
> HAL_msp_init() | Generated in stm32xxx_hal_msp.c and called by HAL_init() | Not used | Generated in stm32xxx_hal_msp.c and called by HAL_init() | This function performs the peripheral resources configuration (1) .
> MX_<Peripheral>_Init() | [1]: Peripheral configuration and call to HAL_<Peripheral>_Init() | [2]: Peripheral and peripheral resource configuration (1) using LL functions. Call to LL_Peripheral_Init() | When HAL driver is selected for the <Peripheral>, follows [1]: Peripheral configuration and call to HAL_<Peripheral>_Init(). When LL driver is selected, follows [2]: Peripheral and peripheral resource configuration using LL functions | This file takes care of the peripherals configuration. When the LL driver is selected for the <Peripheral>, it also performs the peripheral resources configuration (1) .
> HAL_<Peripheral>_MspInit() | [3]: Generated in stm32xxx_hal_msp.c when HAL driver selected for the <Peripheral> | Not used | Only HAL driver can be selected for the <Peripheral>: function generation and calls done following [3]: Generated in stm32xxx_hal_msp.c when HAL driver selected for the <Peripheral> | Peripheral resources configuration (1)
> HAL_<Peripheral>_MspDeInit() | [4]: Generated in stm32xxx_hal_msp.c when HAL driver selected for the <Peripheral> | Not used | Only HAL driver can be selected for the <Peripheral>: function generation and calls done following [4]: Generated in stm32xxx_hal_msp.c when HAL driver selected for the <Peripheral> | This function can be used to free peripheral resources.

> (1) Peripheral resources include: peripheral clock, pinout configuration (GPIOs), peripheral DMA requests, peripheral interrupt requests and priorities. .. rubric:: Figure 567. HAL-based peripheral initialization: usart.c code snippet

> Figure 568. LL-based peripheral initialization: usart.c code snippet

> 6.3 Custom code generation

> STM32CubeMX supports custom code generation by means of a FreeMarker template engine (see http://www.freemarker.org).

> 6.3.1 STM32CubeMX data model for FreeMarker user templates

> STM32CubeMX can generate a custom code based on a FreeMarker template file (.ftl extension) for any of the following MCU configuration information:

> • List of MCU peripherals used by the user configuration

> • List of parameters values for those peripherals

> • List of resources used by these peripherals: GPIO, DMA requests and interrupts.

> The user template file must be compatible with STM32CubeMX data model. This means that the template must start with the following lines:

> [#ftl]

> [#list configs as dt]

> [#assign data = dt]

> [#assign peripheralParams =dt.peripheralParams]

> [#assign peripheralGPIOParams =dt.peripheralGPIOParams]

> [#assign usedIPs =dt.usedIPs] and end with

> [/#list]

> A sample template file is provided for guidance (see Figure 570).

> STM32CubeMX will also generate user-specific code if any is available within the template.

> As shown in the example below, when the sample template is used, the ftl commands are provided as comments next to the data they have generated:

> FreeMarker command in template:

> ${peripheralParams.get(“RCC”).get(“LSI_VALUE”)} Resulting generated code:

> LSI_VALUE : 32000 [peripheralParams.get(“RCC”).get(“LSI_VALUE”)]

> Figure 570. Default content of the extra_templates folder

> 6.3.2 Saving and selecting user templates

> The user can either place the FreeMarker template files under STM32CubeMX installation path within the db/extra_templates folder or in any other folder.

> Then for a given project, the user will select the template files relevant for its project via the Template Settings window accessible from the Code Generator Tab in the Project Manager view menu (see Section 4.11)

> 6.3.3 Custom code generation

> To generate custom code, the user must place the FreeMarker template file under STM32CubeMX installation path within the db/extra_templates folder (see Figure 571).

> The template filename must follow the naming convention <user filename>_<file extension>.ftl in order to generate the corresponding custom file as <user filename>.<file extension>.

> By default, the custom file is generated in the user project root folder, next to the .ioc file (see Figure 572).

> To generate the custom code in a different folder, the user shall match the destination folder tree structure in the extra_template folder (see Figure 573).

> Figure 571. extra_templates folder with user templates

> Figure 572. Project root folder with corresponding custom generated files

> Figure 574. Custom folder with corresponding custom generated files

> 6.4 Additional settings for C project generation

> STM32CubeMX allows specifying additional project settings through the .extSettings file. This file must be placed in the same project folder and at the same level as the .ioc file.

> As an example, additional settings can be used when external tools call STM32CubeMX to generate the project and require specific project settings.

> Possible entries and syntax

> All entries are optional. They are organized under the followings three categories: ProjectFiles, Groups or Others.

> > • [ProjectFiles]: section where to specify additional include directories

> Syntax

> HeaderPath = <include directory 1 path>;< include directory 2 path >

> Example

> HeaderPath=../../IIR_Filter_int32/Inc ;

> • [Groups]: section where to create new groups of files and/or add files to a group Syntax

> <Group name> = <file pathname1>;< file pathname2>

> Example

> Doc=$ PROJ_DIR$\..\readme.txt

> Lib=C:\libraries\mylib1.lib; C:\libraries\mylib2.lib;

> Drivers/BSP/MyRefBoard = C:\MyRefBoard\BSP\board_init.c; C:\MyRefBoard\BSP\board_init.h;

> • [Others]: section where to enable HAL modules and/or specify preprocessor define statements

> > – Enabling preprocessor define statements

> Preprocessor define statements can be specified using the following syntax after the [Others] line:

> Syntax

> Define = <define1_name>;<define2_name>

> Example

> Define= USE_STM32F429I_DISCO

> > – Enabling HAL modules in generated stm32f4xx_hal_conf.h

> HAL modules can be enabled using the following syntax after the [Others] line:

> Syntax

> HALModule = <ModuleName1>; <ModuleName1>;

> Example

> HALModule=I2S;I2C

> .extSettings file example and generated outcomes

> For the purpose of the example, a new project is created by selecting the

> STM32F429I-DISCO board from STM32CubeMX board selector. The EWARM toolchain is selected in the Project tab of the Project Manager view. The project is saved as

> MyF429IDiscoProject. In the project folder, next to the generated .ioc file, a .extSettings text file is placed with the following contents:

> [Groups]

> Drivers/BSP/STM32F429IDISCO=C:\Users\frq09031\STM32Cube\Repository\STM3

> 2Cube_FW_F4_V1.14.0\Drivers\BSP\STM32F429I-

> Discovery\stm32f429i_discovery.c;

> C:\Users\frq09031\STM32Cube\Repository\STM32Cube_FW_F4_V1.14.0\Drivers\

> BSP\STM32F429I-Discovery\stm32f429i_discovery.h

> Lib=C:\Users\frq09031\STM32Cube\Repository\STM32Cube_FW_F4_V1.14.0\

> Middlewares\Third_Party\FreeRTOS\Source\portable\IAR\ARM_CM4F\portasm.s

> Doc=$PROJ_DIR$\..\readme.txt

> [Others]

> Define = USE_ STM32F429I_DISCO

> HALModule = UART;SPI

> Upon project generation, the presence of this .extSettings file triggers the update of:

> • the project MyF429IDiscoProject.ewp file in EWARM folder (see Figure 575)

> • the stm32f4xx_hal_conf.h file in the project Inc folder (see Figure 576)

> • the project view within EWARM user interface as shown in Figure 577 and Figure 578.

> Figure 575. Update of the project .ewp file (EWARM IDE) for preprocessor define statements

> Figure 578. Preprocessor define statements in EWARM IDE

Code generation for dual-core MCUs (STM32H7 dual-core product lines only)

7 Code generation for dual-core MCUs

(STM32H7 dual-core product lines only)

For working with Arm Cortex-M dual-core products, STM32CubeMX generates code for both cores automatically according to the context assignment and initializer choices made in the user interface (see Section 4.8: Pinout & Configuration view for STM32H7 dual-core products for details).

Figure 579. Code generation for STM32H7 dual-core devices

Generated initialization code

The code is generated in CM4, CM7 and Common folders. The Common folder holds the system_stm32h7xx.c, that contains the clock tree settings.

When a peripheral or middleware is assigned to both contexts, the function

MX_<name>_init will be generated for both contexts but will be called only from the initializer side.

Code generation for dual-core MCUs (STM32H7 dual-core product lines only)

Generated startup and linker files

Each configuration (_M4 or _M7) of the project shall come with a startup file and a linker file, each suffixed with _M4 or _M7 respectively.

Figure 580. Startup and linker files for STM32H7 dual-core devices

Generated boot mode code

STM32CubeMX supports only one mode of boot for now, where both ARM Cortex-M cores boot at once.

The other boot modes will be introduced later as a project option in the project manager view:

• Arm Cortex-M7 core booting, Arm Cortex-M4 gated

• Arm Cortex-M4 core booting, Arm Cortex-M7 gated

• A first core booting executing from flash, loads the second core code to the SRAM then enables the second core to boot.

STM32CubeMX uses template files delivered with STM32CubeH7 MCU packages as reference.

Code generation with TrustZone enabled (STM32L5 series only)

8 Code generation with TrustZone enabled (STM32L5 series only)

In STM32CubeMX project manager view, all project generation options remain available.

However, the choice of toolchains is limited to the IDEs/compilers supporting the Cortex ® -M33 core:

• EWARM v8.32 or higher

• MDK-ARM v5.27 or higher (ARM compiler 6)

• STM32CubeIDE (GCC v4.2 or higher)

• Makefile (GCC v4.2 or higher)

Upon product selection, STM32CubeMX requires to choose between enabling TrustZone or not.

• When TrustZone is enabled, STM32CubeMX generates two C projects: one secure and one nonsecure. After compilation, two images are available for download, one for each context.

• When TrustZone is disabled, STM32CubeMX generates a nonsecure C project, as for other products not supporting it.

Specificities

When TrustZone is enabled, the project generation must be adjusted to ensure that secure and nonsecure images can be built.

Figure 581. Building secure and nonsecure images with ARMv8-M TrustZone

Code generation with TrustZone enabled (STM32L5 series only)

When TrustZone is enabled for the project, STM32CubeMX generates three folders:

• NonSecure for nonsecure code

• Secure for secure code

• Secure_nsclib for nonsecure callable region

See Figure 582 (use TZ_BasicStructure_project_inCubeIDE.png) and Figure 583 (use STM32L5_STM32CubeMX_Project_settings_inCubeIDE.png).

Figure 582. Project explorer view for STM32L5 TrustZone enabled projects

Code generation with TrustZone enabled (STM32L5 series only)

Figure 583. Project settings for STM32CubeIDE toolchain

STM32CubeMX also generates specific files, detailed in Table 28.

Table 28. Files generated when TrustZone is enabled

File | Folder | Details
The product core secure/nonsecure partitioning .h “template” file Example: partition_stm32l552xx.h | Secure | Initial setup for secure/nonsecure zones for ARMCM33 based on CMSIS CORE V5.3.1 partition_ARMCM33.h Template. It initializes Security attribution unit (SAU) CTRL register, setup behavior of Sleep and Exception Handling, Floating Point Unit and Interrupt Target.
secure_nsc.h file | Secure_nsclib | Must be filled by the user with the list of nonsecure callable APIs. Templates are available as reference in STM32L5Cube embedded software package in Templates\TrustZone®\Secure_nsclib folders.
System_stm32l5xx_s.c | Secure | CMSIS Cortex-M33 device peripheral access layer system source file to be used in secure application when the system implements security.

Code generation with TrustZone enabled (STM32L5 series only)

Table 28. Files generated when TrustZone is enabled (continued)

File | Folder | Details
System_stm32l5xx_ns.c | NonSecure | CMSIS Cortex-M33 device peripheral access layer system source file to be used in nonsecure application when the system implements security.
STM32L562CETX_FLASH STM32L562CETX_RAM or STM32L552CETX_FLASH STM32L552CETX_RAM | Secure, NonSecure | Linker files for the secure and nonsecure memory layouts. File extensions and naming conventions: – .icf (EWARM) – .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);

** /* USER CODE END 2 */**

> /* Infinite loop */

> /* USER CODE BEGIN WHILE */ while (1)

13 Tutorial 3 - Using the Power Consumption Calculator to optimize the embedded application consumption and more

13.1 Tutorial overview

This tutorial focuses on STM32CubeMX Power Consumption Calculator (Power Consumption Calculator) feature and its benefits to evaluate the impacts of power-saving techniques on a given application sequence.

The key considerations to reduce a given application power consumption are:

• Reducing the operating voltage

• Reducing the time spent in energy consuming modes

It is up to the developer to select a configuration that gives the best compromise between low-power consumption and performance.

• Maximizing the time spent in non-active and low-power modes

• Using the optimal clock configuration

The core should always operate at relatively good speed, since reducing the operating frequency can increase energy consumption if the microcontroller has to remain for a long time in an active operating mode to perform a given operation.

• Enabling only the peripherals relevant for the current application state and clock-gating the others

• When relevant, using the peripherals with low-power features (e.g. waking up the microcontroller with the I2C)

• Minimizing the number of state transitions

• Optimizing memory accesses during code execution

– Prefer code execution from RAM to flash memory

– When relevant, consider aligning CPU frequency with flash memory operating frequency for zero wait states.

The following tutorial shows how the STM32CubeMX Power Consumption Calculator feature can help to tune an application to minimize its power consumption and extend the battery life.

Note: The Power Consumption Calculator does not account for I/O dynamic current consumption and external board components that can also affect current consumption. For this purpose, an “additional consumption” field is provided for the user to specify such consumption value.

13.2 Application example description

The application is designed using the NUCLEO-L476RG board, based on an STM32L476RGTx device, and supplied by a 2.4 V battery.

The main purpose of this application is to perform ADC measurements and transfer the conversion results over UART. It uses:

- Multiple low-power modes: Low-power run, Low-power sleep, Sleep, Stop and Standby • Multiple peripherals: USART, DMA, Timer, COMP, DAC and RTC

  > – The RTC is used to run a calendar and to wake up the CPU from Standby when a specified time has elapsed.

  > – The DMA transfers ADC measurements from ADC to memory

  > – The USART is used in conjunction with the DMA to send/receive data via the virtual COM port and to wake up the CPU from Stop mode.

  > The process to optimize such complex application is to start describing first a functional only sequence then to introduce, on a step by step basis, the low-power features provided by the STM32L476RG microcontroller.

  > 13.3 Using the Power Consumption Calculator

  > 13.3.1 Creating a power sequence

  > Follow the steps below to create the sequence (see Figure 651):

  > 1. Launch STM32CubeMX.

  > 2. Click new project and select the Nucleo-L476RG board from the Board tab.

  > 3. Click the Power Consumption Calculator tab to select the Power Consumption Calculator view. A first sequence is then created as a reference.

  > 4. Adapt it to minimize the overall current consumption. To do this:

  > a) Select 2.4 V VDD power supply. This value can be adjusted on a step by step basis (see Figure 652).

  > b) Select the Li-MnO2 (CR2032) battery. This step is optional. The battery type can be changed later on (see Figure 652).

  > Figure 651. Power Consumption Calculation example

  > Figure 652. VDD and battery selection menu

  > 5. Enable the Transition checker to ensure the sequence is valid (see Figure 652). This option allows verifying that the sequence respects the allowed transitions implemented within the STM32L476RG.

  > 6. Click the Add button to add steps that match the sequence described in Figure 652.

  > – By default the steps last 1 ms each, except for the wake-up transitions preset using the transition times specified in the product datasheet (see Figure 653).

  > – Some peripherals for which consumption is unavailable or negligible are highlighted with * (see Figure 653).

  > 7. Click the Save button to save the sequence as SequenceOne.

  > The application consumption profile is generated. It shows that the overall sequence consumes an average of 2.01 mA for 9 ms, and that the battery lifetime is only four days (see Figure 654).

  > Figure 654. sequence results before optimization

  > 13.3.2 Optimizing application power consumption

  > Let us now take actions to optimize the overall consumption and the battery lifetime. These actions are performed on steps 1, 4, 5, 6, 7, 8, and 10.

  > The next figures show on the left the original step, and on the right the step updated with optimization actions.

  > Step 1 (Run) - Findings

  > All peripherals are enabled although the application requires only the RTC.

  > • Actions

  > – Lower the operating frequency

  > – Enable only the RTC peripheral

  > – To reduce the average current consumption, reduce the time spent in this mode

  > • Result

  > The current is reduced from 9.05 to 2.16 mA (see Figure 655).

  > Figure 655. Step 1 optimization

  > Step 4 (Run, RTC) • Action

  > Reduce the time spent in this mode to 0.1 ms

  > Step 5 (Run, ADC, DMA, RTC)

  > • Actions

  > – Change to Low-power run mode

  > – Lower the operating frequency

  > • Results

  > The current consumption is reduced from 6.17 mA to 271 µA (see Figure 656).

  > Figure 656. Step 5 optimization

  > Step 6 (Sleep, DMA, ADC, RTC)

  > • Actions

  > – Switch to Lower-power sleep mode (BAM mode)

  > – Reduce the operating frequency to 2 MHz

  > • Results

  > The current consumption is reduced from 703 µA to 93 µA (see Figure 657).

  > Figure 657. Step 6 optimization

  > Step 7 (Run, DMA, RTC, USART)

  > • Actions

  > – Switch to Low-power run mode

  > – Use the power efficient LPUART peripheral

  > – Reduce the operating frequency to 1 MHz using the interpolation feature

  > • Results

  > The current consumption is reduced from 1.92 mA to 42 µA (see Figure 658).

  > Figure 658. Step 7 optimization

  > |image588|

  > Step 8 (Stop 0, USART) • Actions

  > – Switch to Stop1 low-power mode

  > – Use the power-efficient LPUART peripheral

  > > • Results

  > The current consumption is reduced (see Figure 659).

  > Figure 659. Step 8 optimization

  > Step 10 (RTC, USART) • Actions

  > – Use the power-efficient LPUART peripheral

  > – Reduce the operating frequency to 1 MHz

  > > • Results

  > The current consumption is reduced from 1.89 mA to 234 µA (see Figure 660).

  > The example given in Figure 661 shows an average current consumption reduction of 155 µA.

  > See Figure 661 for the overall results: 7 ms duration, about two months battery life, and an average current consumption of 165.25 µA.

  > Use the compare button to compare the current results to the original ones saved as SequenceOne.pcs.

  > Figure 661. Power sequence results after optimizations

14 Tutorial 4 - Example of UART communications with

an STM32L053xx Nucleo board

This tutorial aims at demonstrating how to use STM32CubeMX to create a UART serial communication application for a NUCLEO-L053R8 board.

A Windows PC is required for the example. The ST-Link USB connector is used both for serial data communications, and firmware downloading and debugging on the MCU. A Type-A to mini-B USB cable must be connected between the board and the computer. The USART2 peripheral uses PA2 and PA3 pins, which are wired to the ST-Link connector. In addition, USART2 is selected to communicate with the PC via the ST-Link Virtual COM Port. A serial communication client, such as Tera Term, needs to be installed on the PC to display the messages received from the board over the virtual communication Port.

14.1 Tutorial overview

Tutorial 4 will take you through the following steps:

1. Selection of the NUCLEO-L053R8 board from the New Project menu.

2. Selection of the required features (debug, USART, timer) from the Pinout view:

peripheral operating modes as well as assignment of relevant signals on pins.

3. Configuration of the MCU clock tree from the Clock Configuration view.

4. Configuration of the peripheral parameters from the Configuration view

5. Configuration of the project settings in the Project Manager menu and generation of the project (initialization code only).

6. Project update with the user application code corresponding to the UART communication example.

7. Compilation, and execution of the project on the board.

8. Configuration of Tera Term software as serial communication client on the PC.

9. The results are displayed on the PC.

14.2 Creating a new STM32CubeMX project and

selecting the Nucleo board

To do this, follow the sequence below:

1. Select File > New project from the main menu bar. This opens the New Project window.

2. Go to the Board selector tab and filter on STM32L0 series.

3. Select NUCLEO-L053R8 and click OK to load the board within the STM32CubeMX user interface (see Figure 662).

Figure 662. Selecting NUCLEO_L053R8 board

14.3 Selecting the features from the Pinout view

1. Select Debug Serial Wire under SYS (see Figure 663).

Figure 663. Selecting debug pins

2. Select Internal Clock as clock source under TIM2 peripheral (see Figure 664).

Figure 664. Selecting TIM2 clock source

> 3. Select the Asynchronous mode for the USART2 peripheral (see Figure 665).

Figure 665. Selecting asynchronous mode for USART2

> 4. Check that the signals are properly assigned on pins (see Figure 666):

– SYS_SWDIO on PA13

– TCK on PA14

– USART_TX on PA2

– USART_RX on PA3

14.4 Configuring the MCU clock tree from the Clock Configuration view

1. Go to the Clock Configuration tab and leave the configuration untouched, in order to use the MSI as input clock and an HCLK of 2.097 MHz (see Figure 667).

Figure 667. Configuring the MCU clock tree

14.5 Configuring the peripheral parameters from the Configuration view

1. From the Configuration tab, click USART2 to open the peripheral Parameter Settings window and set the baud rate to 9600. Make sure the Data direction is set to “Receive and Transmit” (see Figure 668).

2. Click OK to apply the changes and close the window.

Figure 668. Configuring USART2 parameters

3. Click TIM2 and change the prescaler to 16000, the Word Length to 8 bits and the Counter Period to 1000 (see Figure 669).

4. Enable TIM2 global interrupt from the NVIC Settings tab (see Figure 670).

Figure 670. Enabling TIM2 interrupt

14.6 Configuring the project settings and generating the project

1. In the Project Settings menu, specify project name and destination folder, and select the EWARM IDE toolchain (see Figure 671).

If the firmware package version is not already available on the user PC, a progress window opens to show the download progress.

2. In the Code Generator tab, configure the code to generate as shown in Figure 672, and click OK to generate it.

14.7 Updating the project with the user application code

Add the user code as follows:

/* USER CODE BEGIN 0 */

#include “stdio.h”

#include “string.h”

/* Buffer used for transmission and number of transmissions */ char aTxBuffer[1024]; int nbtime=1;

/* USER CODE END 0 */

Within the main function, start the timer event generation function as follows:

/* USER CODE BEGIN 2 */

** /* Start Timer event generation */**

** HAL_TIM_Base_Start_IT(&htim2);**

** /* USER CODE END 2 */**

/* USER CODE BEGIN 4 */ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim){ sprintf(aTxBuffer,”STM32CubeMX rocks %d times \t”, ++nbtime);

HAL_UART_Transmit(&huart2,(uint8_t *) aTxBuffer, strlen(aTxBuffer), 5000); }

/* USER CODE END 4 */

14.8 Compiling and running the project

1. Compile the project within your favorite IDE.

2. Download it to the board.

3. Run the program.

14.9 Configuring Tera Term software as serial communication

client on the PC

1. On the computer, check the virtual communication port used by ST Microelectronics from the Device Manager window (see Figure 673).

|image603|

2. To configure Tera Term to listen to the relevant virtual communication port, adjust the parameters to match the USART2 parameter configuration on the MCU (see Figure 674).

Figure 674. Setting Tera Term port parameters

|image604|

3. The Tera Term window displays a message coming from the board at a period of a few seconds (see Figure 675).

Figure 675. Setting Tera Term port parameters

|image605|

Tutorial 5: Exporting current project configuration to a compatible MCU

15 Tutorial 5: Exporting current project configuration to

a compatible MCU

When List pinout compatible MCUs is selected from the Pinout menu, STM32CubeMX retrieves the list of the MCUs which are compatible with the current project configuration, and offers to export the current configuration to the newly selected compatible MCU.

This tutorial shows how to display the list of compatible MCUs and export your current project configuration to a compatible MCU:

1. Load an existing project, or create and save a new project:

Figure 676. Existing or new project pinout

|image606|

2. Go to the Pinout menu and select List Pinout Compatible MCUs. The Pinout compatible window pops up (see Figure 677 and Figure 678).

If needed, modify the search criteria and the filter options and restart the search process by clicking the Search button.

The color shading and the Comments column indicate the level of matching:

– Exact match: the MCU is fully compatible with the current project (see Figure 678 for an example).

– Partial match with hardware compatibility: the hardware compatibility can be ensured but some pin names could not be preserved. Hover the mouse over the desired MCU to display an explanatory tooltip (see Figure 677 for an example).

Tutorial 5: Exporting current project configuration to a compatible MCU

– Partial match without hardware compatibility: not all signals can be assigned to the exact same pin location and a remapping will be required. Hover the mouse over the desired MCU to display an explanatory tooltip (see Figure 678 for an example).

Figure 677. List of pinout compatible MCUs - Partial match with hardware compatibility

|image607|

Tutorial 5: Exporting current project configuration to a compatible MCU

3. Select an MCU to import the current configuration to, and click OK, Import:

Figure 679. Selecting a compatible MCU and importing the configuration

|image608|

The configuration is now available for the selected MCU:

Figure 680. Configuration imported to the selected compatible MCU

|image609|

Tutorial 5: Exporting current project configuration to a compatible MCU

4. To see the list of compatible MCUs, select Outputs under the Window menu.

To load the current configuration to another compatible MCU, double-click the list of compatible MCUs.

5. To remove some constraints on the search criteria, several solutions are possible:

– Select the Ignore Pinning Status checkbox to ignore pin status (locked pins).

– Select the Ignore Power Pins checkbox to not take into account the power pins.

– Select the Ignore System Pins to not take into account the system pins. Hover the mouse over the checkbox to display a tooltip that lists the system pins available on the current MCU.

Note: The option “List of Compatible MCU” is available only for single-core products, and grayed out for dual-core microcontrollers, as exemplified in Figure 681.

Figure 681. Import configuration not available for dual core MCUs

|image610|

Tutorial 6 – Adding embedded software packs to user projects

16 Tutorial 6 – Adding embedded software packs to user projects

In this tutorial, the Oryx-Embedded.Middleware.1.7.8. pack is taken as an example to demonstrate how to a to add pack software components to STM32CubeMX projects. The use of this package shall not be understood as an STMicroelectronics recommendation.

To add embedded software packs to your project, proceed as follows:

1. Install Oryx-Embedded.Middleware.1.7.8.pack using the .pdsc file available from http://www.oryx-embedded.com (see Section 3.4.5: Installing embedded software packs).

2. Select New project.

3. Select STM32F01CCFx from the MCU selector.

4. Select Additional Software from the Pinout & Configuration view to open the additional software component window and choose the following software components: Compiler Support, RTOS Port/None and Date Time Helper Routines from the CycloneCommon bundle (see Section 4.15: Software Packs component selection window).

5. Click OK to display the selected components on the tree view and click the checkbox to enable the software components for the current project (see Figure 682).

Figure 682. Additional software components enabled for the current project

|image611|

The pack name highlighted in green indicates that all conditions for the selected software components resolve to true. If at least one condition is not resolved, the pack name is highlighted in orange.

Tutorial 6 – Adding embedded software packs to user projects

6. Check that no parameters can be configured in the Configuration tab (see Figure 683).

Figure 683. Pack software components: no configurable parameters

|image612|

7. Select the Project manager project tab to specify project parameters (see Figure 684), and choose IAR™ EWARM as IDE.

|image613|

Tutorial 6 – Adding embedded software packs to user projects

8. Generate your project by clicking . Accept to download the

STM32CubeF4 MCU package if it is not present in STM32Cube repository.

9. Click Open project. The Oryx software components are displayed in the generated project (see Figure 685).

Figure 685. Generated project with third party pack components

|image614|

17 Tutorial 7 – Using the X-Cube-BLE1 software pack

This tutorial demonstrates how to achieve a functional project using the X-Cube-BLE1 software pack.

Below the prerequisites to run this tutorial:

• Hardware: NUCLEO-L053R8, X-NUCLEO-IDB05A1 and mini-USB cable (see Figure 686)

• Tools: STM32CubeMX, IDE (Atollic ® or any other toolchain supported by STM32CubeMX)

• Embedded software package: STM32CubeL0 (version 1.10.0 or higher), X-Cube-BLE1

1.1.0 (see Figure 687).

• Mobile application (see Figure 688): STMicroelectronics BlueNRG application for iOS ® or Android ™

|image615|

Figure 687. Embedded software packages

|image616|

|image617|

Proceed as follows to install and run the tutorial:

1. Check STM32CubeMX Internet connection:

a) Select the Help > Updater Settings menu to open the updater window.

b) Verify in the Connection tab that the Internet connection is configured and up.

2. Install the required embedded software packages (see Figure 689):

a) Select the Help > Manage Embedded software packages menu to open the embedded software package manager window.

b) Click the Refresh button to refresh the list with the latest available package versions.

c) Select the STM32Cube MCU Package tab and check that the STM32CubeL0 firmware package version 1.10.0 or higher is installed (the checkbox must be green). Otherwise select the checkbox and click Install now.

d) Select the STMicrolectronics tab and check that the X-Cube-BLE1 software pack version 1.0.0 is installed (checkbox must be green). Otherwise, select the checkbox and click Install now.

Figure 689. Installing Embedded software packages

|image618|

3. Start a new project:

a) Select New Project to open the new project window.

b) Select the Board selector tab.

c) Select Nucleo64 as board type and STM32L0 as MCU Series.

d) Select the NUCLEO-L053R8 from the resulting board list (see Figure 690).

e) Answer No when prompted to initialize all peripherals in their default mode (see Figure 691).

Figure 690. Starting a new project - selecting the NUCLEO-L053R8 board

|image619|

4. Add X-Cube-BLE1 components to the project:

a) Click Additional Software from Pinout & Configuration view to open the Additional Software component Selection window.

b) Select the relevant components (see Figure 692)

The Application group comes with a list of applications: the C files implement the application loop, that is the Process() function. From the Application group, select the SensorDemo application.

Select the Controller and Utils components

Select the Basic variant for the HCI_TL component . The Basic variant provides the STMicroelectronics implementation of the HCI_TL API while the template option requires users to implement their own code.

Select the UserBoard variant as HCI_TL_INTERFACE component. Using the UserBoard option generates the <boardname>_bus.c file, that is nucleo_l053r8_bus.c for this tutorial, while the template option generates the custom_bus.c file and requires users to provide their own implementation.

Refer to the X-Cube-BLE1 pack documentation for more details on software components.

3. Click OK to apply the selection to the project and close the window. The left panel Additional Software section is updated accordingly.

Figure 692. Selecting X-Cube-BLE1 components

|image620|

5. Enable peripherals and GPIOs from the Pinout tab (see Figure 693):

a) Configure USART2 in Asynchronous mode.

b) Configure SPI1 in Full-duplex master mode.

c) Left-click the following pins and configure them for the required GPIO settings:

PA0: GPIO_EXTI0

PA1: GPIO_Output

PA8: GPIO_Output

d) Enable Debug Serial Wire under SYS peripheral.

Figure 693. Configuring peripherals and GPIOs

|image621|

6. Configure the peripherals from the Configuration tab:

a) Click the NVIC button under the System section to open the NVIC configuration window. Enable EXTI line 0 and line 1 interrupts and click OK (see Figure 694).

b) Click the SPI button under the Connectivity section to open the SPI configuration window. Check that the data size is set to 8 bits and the prescaler value to 16 so that HCLK divided by the prescaler value is less or equal to 8 MHz.

c) Click USART2 under the Connectivity section to open the Configuration window and check the following parameter settings:

Under Parameter Settings:

Baud rate: 115200 bits/s

Word length: 8 bits (including parity) Parity: none

Stop bits: 1

Under GPIO Settings:

User labels: USART_TX and USART_RX

Figure 694. Configuring NVIC interrupts

|image622|

7. Enable and configure X-Cube-BLE1 pack components from the Pinout & Configuration view:

a) Click the pack items from the left panel to show the mode and configuration tabs.

b) Click the check boxes from the Mode panel to enable X-Cube-BLE1, the configuration panel appears showing the parameters to configure. An orange triangle indicates that some parameters are not configured. It turns into a green check mark once all parameters are correctly configured (see Figure 695).

c) Leave the Parameter Settings Tab unchanged.

d) Go the Platform settings tab, configure the connection with the hardware resources as indicated in Figure 695 and Table 29.

Table 29. Connection with hardware resources

Name | IPs or components | Found solutions
BUS IO driver | SPI in Full-duplex master mode | SPI1
EXTI Line | GPIO:EXTI | PA0
CS Line | GPIO:output | PA1
Reset Line | GPIO:output | PA8
BSP LED | GPIO:output | PA5
BSP Button | GPIO:EXTI | PC13
BSP USART | USART in Asynchronous mode | USART2

Check that the icon turns to . Click OK to close the Configuration window .

Figure 695. Enabling X-Cube-BLE1

|image623|

8. Generate the SensorDemo project:

a) Click ** to generate the code. The **Project Settings window opens if the project has not yet been saved.

b) Click ** ** to generate the code once the project settings have

been properly configured (see Figure 696). When the generation is complete, a dialog window requests to open the project folder (Open Folder) or to open the project in IDE toolchain (Open Project). Select Open Project (see Figure 697).

Figure 696. Configuring the SensorDemo project

|image624|