DATASHEET SEARCH SITE | WWW.ALLDATASHEET.COM

Document overview

  • Manufacturer or author: Provided By ALLDATASHEET.COM(FREE DATASHEET DOWNLOAD SITE)
  • PDF pages: 231

Technical content

Datasheet sections

  • 1 STM32Cube overview
  • 2 Getting started with STM32CubeM X
  • 2.1 Principles
  • 2.2 Key features
  • 2.3 Rules and limitations
  • 3 Installing and running STM32CubeMX
  • 3.1 System requirements
  • 3.1.1 Supported operating systems and architec tures
  • 3.1.2 Memory prerequisites
  • 3.1.3 Software requirements
  • 3.2 Installing/uninstalling STM32CubeMX standalone version
  • 3.2.1 Installing STM32CubeMX standalone version
  • 3.2.2 Installing STM32CubeMX from command line
  • 3.2.3 Uninstalling STM32CubeMX standalone version
  • 3.3 Installing STM32CubeMX plug-in version
  • 3.3.1 Downloading STM32CubeMX plug-in installation package
  • 3.3.2 Installing STM32CubeMX as an Eclipse ID E plug-in
  • 3.3.3 Uninstalling STM32CubeMX as Eclipse IDE plug-in
  • 3.4 Launching STM32CubeMX
  • 3.4.1 Running STM32CubeMX as standalone application
  • 3.4.2 Running STM32CubeMX in command-line mode
  • 3.4.3 Running STM32CubeMX plug-in from Eclip se IDE
  • 3.5 Getting STM32Cube updates
  • 3.5.1 Updater configuration
  • 3.5.2 Downloading new libraries
  • 3.5.3 Removing libraries
  • 3.5.4 Checking for updates
  • 4 STM32CubeMX User Interface
  • 4.1 Welcome page
  • 4.2 New project window

Datasheet sections

  • 4.13.4 Clock tree glossary
  • 4.14 Power Consumption Calculator (PCC) view
  • 4.14.1 Building a power consumption sequence
  • 4.14.2 Configuring a step in the power sequence
  • 4.14.3 Managing user-defined power sequence and reviewing results
  • 4.14.4 Power sequence step parameters glossary
  • 4.14.5 Battery glossary
  • 5 STM32CubeMX C Code generation overview
  • 5.1 Standard STM32Cube code generation
  • 5.2 Custom code generation
  • 5.2.1 STM32CubeMX data model for FreeMa rker user templates
  • 5.2.2 Saving and selecting user templates
  • 5.2.3 Custom code generation
  • 6 Tutorial 1: From pinout to project C code generation
  • 6.1 Creating a new STM32CubeMX Project
  • 6.2 Configuring the MCU pinout
  • 6.3 Saving the project
  • 6.4 Generating the report
  • 6.5 Configuring the MCU Clock tree
  • 6.6 Configuring the MCU initialization parameters
  • 6.6.1 Initial conditions
  • 6.6.2 Configuring the peripherals
  • 6.6.3 Configuring the GPIOs
  • 6.6.4 Configuring the DMAs
  • 6.6.5 Configuring the middleware
  • 6.7 Generating a complete C project
  • 6.7.1 Setting project options
  • 6.7.2 Downloading firmware package and generating the C code
  • 6.8 Building and updating the C code project
  • 6.9 Switching to another MCU
  • 7 Tutorial 2 - Example of FatFs on an SD card using

Datasheet sections

  • 10 Revision history

STM32CubeMX for STM32 configuration and initialization C code generation Introduction STM32CubeMX is a graphical tool for 32-bit ARM® Cortex® STM32 microcontrollers. It is part of STMCube™ initiative (see Section 1) and is available either as a standalone application or as an Eclipse plug-in for integration in Integrated Development Environments (IDEs). STM32CubeMX has the following key features:

  • Easy microcontroller selection covering whole STM32 portfolio.
  • Board selection from a list of STMicroelectronics boards.
  • Easy microcontroller configuration (pins, clock tree, peripherals, middleware) and generation of the corresponding initialization C code.
  • Easy switching to another microcontroller belonging to the same series by importing a previously-saved configuration to a new MCU project.
  • Generation of configuration reports.
  • Generation of IDE ready projects for a selection of integrated development environment tool chains. STM32CubeMX projects include the generated initialization C code, STM32 HAL drivers, the middleware stacks required for the user configuration, and all the relevant files needed to open and build the project in the selected IDE.
  • Power consumption calculation for a user-defined application sequence.
  • Self-updates allowing the user to keep the STM32CubeMX up-to-date.
  • Download and update of STM32Cube ™ embedded software required for user application development (see Appendix E: STM32Cube embedded software packages for details on STM32Cube embedded software offer). Although STM32CubeMX offers a user interface and generates a C code compliant with STM32 MCU design and firmware solutions, it is recommended to refer to the product technical documentation for details on actual implementation of microcontroller peripherals and firmware. Reference documents The following documents are available from http://www.st.com:
  • STM32 microcontroller reference manuals
  • STM32 microcontroller datasheets
  • STM32Cube HAL driver user manuals for STM32F0 (UM1785), STM32F1 (UM1850), STM32F2 (UM1940), STM32F3 (UM1786), STM32F4 (UM1725), STM32F7 (UM1905), STM32L0 (UM1749), STM32L1 (UM1816) and STM32L4 (UM1884).

8 Tutorial 3- Using PCC to optimize the embedded

9.1 On the Pinout configuration pane, why does STM32CubeMX

9.3 Why are some pins highlighted in yellow or in light green in

the Chip view? Why cannot I change the function of some

9.4 Why do I get the error “Java 7 update 45’ when installing

9.5 Why does the RTC multiplexer remain inactive on the Clock tree view? 196

9.6 How can I select LSE and HSE as clock source and

9.7 Why STM32CubeMX does not allow me to configure PC13,

PC14, PC15 and PI8 as outputs when one of them A.6 Block shifting (only for STM32F10x and when

1 STM32Cube overview

STMCube™ is an STMicroelectronics original initiative to ease developers life by reducing development efforts, time and cost. STM32Cube covers STM32 portfolio. STM32Cube includes:

  • The STM32CubeMX, a graphical software configuration tool that allows to generate C initialization C code using graphical wizards.
  • A comprehensive embedded software platform, delivered per series (such as STM32CubeF2 for STM32F2 series and STM32CubeF4 for STM32F4 series) – The STM32Cube HAL, an STM32 abstraction layer embedded software, ensuring maximized portability across STM32 portfolio – A consistent set of middleware components such as RTOS, USB, TCP/IP, Graphics – All embedded software utilities comi ng with a full set of examples.

Getting started with STM32CubeMX UM1718

2 Getting started with STM32CubeMX

2.1 Principles

Customers need to quickly identify the MCU that best meets their requirements (core architecture, features, memory size, performance…). While board designers main concerns are to optimize the microcontroller pin configuration for their board layout and to fulfill the application requirements (choice of peripherals operating modes), embedded system developers are more interested in developing new applications for a specific target device, and migrating existing designs to different microcontrollers. The time taken to migrate to new platforms and update the C code to new firmware drivers adds unnecessary delays to the project. STM32CubeMX was developed within STM32Cube initiative which purpose is to meet customer key requirements to maximize software reuse and minimize the time to create the target system:

  • Software reuse and application design portability are achieved through STM32Cube firmware solution proposing a common Hardware Abstraction Layer API across STM32 portfolio.
  • Optimized migration time is achieved thanks to STM32CubeMX built-in knowledge of STM32 microcontrollers, peripherals and middleware (LwIP and USB communication protocol stacks, FatFs file system for small embedded systems, FreeRTOS). STM32CubeMX graphical interface performs the following functions:
  • Fast and easy configuration of the MCU pins, clock tree and operating modes for the selected peripherals and middleware
  • Generation of pin configuration report for board designers
  • Generation of a complete project with all the necessary libraries and initialization C code to set up the device in the user defined operating mode. The project can be directly open in the selected application development environment (for a selection of supported IDEs) to proceed with application development (see Figure 1). During the configuration process, STM32CubeMX detects conflicts and invalid settings and highlights them through meaningful icons and useful tool tips.

Figure 1. Overview of STM32CubeMX C code generation flow

Getting started with STM32CubeMX UM1718

2.2 Key features

STM32CubeMX comes with the following features:

  • Project management STM32CubeMX allows creating, saving and loading previously saved projects: – When STM32CubeMX is launched, the user can choose to create a new project or to load a previously saved project. – Saving the project saves user settings and configuration performed within the project in an .ioc file that will be used the next time the project will be loaded in STM32CubeMX. STM32CubeMX also allows importing previously saved projects in new projects. STM32CubeMX projects come in two flavors: – MCU configuration only: .ioc file are saved anywhere, next to other .ioc files. – MCU configuration with C code generation: in this case .ioc files are saved in a dedicated project folder along with the generated source C code. There can be only one .ioc file per project.
  • Easy MCU and STMicroelectronics board selection When starting a new project, a dedicated window opens to select either a microcontroller or an STMicroelectronics board from STM32 portfolio. Different filtering options are available to ease the MCU and board selection.
  • Easy pinout configuration – From the Pinout view, the user can select the peripherals from a list and configure the peripheral modes required for the application. STM32CubeMX assigns and configures the pins accordingly. – For more advanced users, it is also poss ible to directly map a peripheral function to a physical pin using the Chip view. The signals can be locked on pins to prevent STM32CubeMX conflict solver from moving the signal to another pin. – Pinout configuration can be exported as a .csv file.
  • Complete project generation The project generation includes pinout, firmware and middleware initialization C code for a set of IDEs. It is based on STM32Cube embedded software libraries. The following actions can be performed: – Starting from the previously defined pinout, the user can proceed with the configuration of middleware, clock tree, services (RNG, CRC, etc...) and IP peripheral parameters. STM32CubeMX generates the corresponding initialization C code. The result is a project directory including generated main.c file and C header files for configuration and initialization, plus a copy of the necessary HAL and middleware libraries as well as specific files for the selected IDE. – The user can modify the generated source files by adding user-defined C code in user dedicated sections. STM32CubeMX ensures that the user C code is preserved upon next C code generation (the user C code is commented if it is no longer relevant for the current configuration). – STM32CubeMX can generate user files by using user-defined freemarker .ftl template files. – From the Project settings menu, the user can select the development tool chain (IDE) for which the C code has to be generated. STM32CubeMX ensures that the IDE relevant project files are added to the project folder so that the project can be

UM1718 Getting started with STM32CubeMX 230 directly imported as a new project within third party IDE (IAR™ EWARM, Keil™ MDK-ARM, Atollic® TrueSTUDIO and AC6 System Workbench for STM32).

  • Power consumption calculation Starting with the selection of a microcontroller part number and a battery type, the user can define a sequence of steps representing the application life cycle and parameters (choice of frequencies, enabled peripherals, step duration). STM32CubeMX Power Consumption Calculator returns the corresponding power consumption and battery life estimates.
  • Clock tree configuration STM32CubeMX offers a graphical representation of the clock tree as it can be found in the device reference manual. The user can change the default settings (clock sources, prescaler and frequency values). The clock tree is then updated accordingly. Invalid settings and limitations are highlighted and documented with tool tips. Clock tree configuration conflicts can be solved by using the solver feature. When no exact match is found for a given user configuration, STM32CubeMX proposes the closest solution.
  • Automatic updates of STM32CubeMX and STM32Cube firmware packages STM32CubeMX comes with an updater mechanism that can be configured for automatic or on-demand check for updates. It supports STM32CubeMX self-updates as well as STM32Cube firmware library package updates. The updater mechanism also allows deleting previously installed packages.
  • Report generation .pdf and .csv reports can be generated to document user configuration work.

2.3 Rules and limitations

  • C code generation covers only peripheral and middleware initialization. It is based on STM32Cube HAL firmware libraries.
  • STM32CubeMX C code generation covers only initialization code for peripherals and middlewares that use the drivers included in STM32Cube embedded software packages. The code generation of some peripherals and middlewares, such as cryptographic IPs and StemWin graphic library, is not yet supported.
  • Refer to Appendix A for a description of pin assignment rules.
  • Refer to Appendix B for a description of STM32CubeMX C code generation design choices and limitations.

Installing and running STM32CubeMX UM1718

3 Installing and running STM32CubeMX

3.1 System requirements

3.1.1 Supported operating systems and architectures

  • Windows® XP: 32-bit (x86)
  • Windows® 7: 32-bit (x86), 64-bit (x64)
  • Windows® 8: 32-bit (x86), 64-bit (x64)
  • Linux®: 32-bit (x86) and 64-bit (x64) (tested on RedHat, Ubuntu and Fedora)
  • MacOS: 64-bit (x64) (tested on OS X Yosemite)

3.1.2 Memory prerequisites

  • Recommended minimum RAM: 2 Gbytes.

3.1.3 Software requirements

The following software must be installed:

  • Java Run Time Environment for 1.7.0_45 If Java is not installed on your computer or if you have an old version, STM32CubeMX installer will open the Java download web page and stop.
  • For Eclipse plug-in installation only, install one of the following IDE: – Eclipse IDE Juno (4.2) – Eclipse Luna (4.4) – Eclipse Kepler (4.3) – Eclipse Mars (4.5)

3.2 Installing/uninstalling STM 32CubeMX standalone version

3.2.1 Installing STM32CubeMX standalone version

To install STM32CubeMX, follow the steps below: 1. Download STM32CubeMX installation pa ckage from www.st.com/stm32cubemx. 2. Extract (unzip) stm32cubemx.zip wh ole package into the same directory. 3. Check your access rights and launch the installation wizard: On windows: a) Make sure you have administrators rights. b) Double click the SetupSTM32CubeMX-VERSION .exe file to launch the installation wizard. On Linux: a) Make sure you have access rights to the target installation director. You can run the installation as root (or sudo) to install STM32CubeMX in shared directories.

UM1718 Installing and running STM32CubeMX 230 b) Double click (or launch from the console window) on the SetupSTM32CubeMX- VERSION.linux file. On MacOS: a) Make sure you have administrators rights. b) Double click SetupSTM32CubeMX applic ation file to launch the installation wizard. 4. Upon successful installation of STM32C ubeMX on Windows, STM32CubeMX icon is displayed on your desktop and STM32CubeMX application is available from the Program menu. STM32CubeMX .ioc files are displayed with a cube icon. Double-click them to open up them using STM32CubeMX. 5. Delete the content of the zip from your disk. Note: If the proper version of the Java Runtime Environment (version 1.7_45 or newer) is not installed, the wizard will propose to download it and stop. Restart STM32CubeMX installation once Java installation is complete. Refer to Section 9: FAQ for issues when installing the JRE. When working on Windows, only the latest installation of STM32CubeMX will be enabled in the program menu. Previous versions can be kept on your PC (not recommended) when different installation folders have been specified. Otherwise, the new installation overwrites the previous ones.

3.2.2 Installing STM32C ubeMX from command line

There are 2 ways to launch an installation from a console window: either in console interactive mode or via a script. Interactive mode To perform interactive installation, type the following command: java –jar SetupSTM32CubeMX-4.14.0.exe –console At each installation step, an answer is requested (see Figure 2 below).

Figure 2. Example of STM32CubeMX installation in interactive mode

Figure 3. STM32Cube Installation Wizard

Figure 4. Auto-install command line

3.2.3 Uninstalling STM32CubeMX standalone version

  1. Open the Windows Control panel .
  2. Select Programs and Features to display the list of programs installed on your
  3. Right click on STM32CubeMX and select the uninstall function.
  • Use a file explorer, go to the Uninstaller directory of the STM32CubeMX installation, and double click the startuninstall desktop shortcut.
  • or launch manually the uninstallation with java -jar <install path>/Uninstaller/uninstaller.jar.

3.3 Installing STM32C ubeMX plug-in version

STM32CubeMX plug-in can be installed within Eclipse IDE development tool chain. Installation related procedures are described in this section.

3.3.1 Downloading STM32CubeMX plug-in installation package

  1. Go to http://www.st.com/stm32cubemx.
  2. Download STM32CubeMX- Eclipse-plug- in .zip file to your local disk.

3.3.2 Installing STM32CubeMX as an Eclipse IDE plug-in

  1. Launch the Eclipse environment.
  2. Select Help > Install New Software from the main menu bar. The Available Software
  3. Click Add. The Add Repository window opens.
  4. Click Archive. The Reposit ory archive browser opens.
  5. Select the STM32CubeMX- Eclipse-plug-in .zip file that you downloaded and click
  6. Click OK in the Add Repository dialog box,
  7. Check STM32CubeMX_Eclipse_plug-in and click Next (see Figure 6).
  8. Click Next in the Inst all Details dialog box.
  9. Click ”I accept the terms of the license agreement” in the Review Licenses dialog box
  10. Click OK in the Security Warning menu.
  11. Click OK when requested to restart Eclipse IDE (see Section 3.4.2: Running

STM32CubeMX in command-line mode). Figure 5. Adding STM32CubeMX plug-in archive

Figure 6. Installing STM32CubeMX plug-in

3.3.3 Uninstalling STM32Cub eMX as Eclipse IDE plug-in

  1. In Eclipse, right-click STM32CubeMX perspective Icon (see Figure 7) and select Close.
  2. From Eclipse Help menu, select Install New Software.
  3. Click Installed Software tab, then select STM32CubeMX and click Uninstall.
  4. Click Finish in Uninstall Details menu (see Figure 8).

Figure 7. Closing STM32CubeMX perspective

Figure 8. Uninstalling STM32CubeMX plug-in

Installing and running STM32CubeMX UM1718

3.4 Launching STM32CubeMX

3.4.1 Running STM32CubeMX as standalone application

To run STM32CubeMX as a standalone application on Windows:

  • select STM32CubeMX from Program Files > ST Microelectronics > STM32CubeMX.
  • or double-click STM32CubeMX icon on your desktop. To run STM32CubeMX as a standalone application on Linux, launch the STM32CubeMX executable from STM32CubeMX installation directory.

3.4.2 Running STM32CubeMX in command-line mode

To facilitate its integration with other tools, STM32CubeMX provides a command-line mode. Using a set of commands, you can:

  • Load an MCU
  • Load an existing configuration
  • Save a current configuration
  • Set project parameters and generate corresponding code
  • Generate user code from templates. Three command-line modes are available:
  • To run STM32CubeMX in interactive command-line mode, use the following command line: – On Windows: java -jar STM32CubeMX.exe –i – On Linux and MacOS: java -jar STM32CubeMX –i The “MX>” prompt is then displayed to indicate that the application is ready to accept commands.
  • To run STM32CubeMX in command-line mode getting commands from a script, use the following command line: – On Windows: java -jar STM32CubeMX.exe –s <script filename> – On Linux and MacOS: java -jar STM32CubeMX –s <script filename> All the commands to be executed must be listed in the script file. An example of script file content is shown below: load STM32F417VETx project name MyFirstMXGeneratedProject project toolchain "MDK-ARM v4" project path C:\\STM32CubeProjects\\STM32F417VETx project generate exit
  • To run STM32CubeMX in command-line mode getting commands from a scripts and without UI, use the following command line: – On Windows: java -jar STM32CubeMX.exe –q <script filename> – On Linux and MacOS: java -jar STM32CubeMX –q <script filename> Here again, the user can enter commands when the MX prompt is displayed. See Table 1 for available commands.

Table 1. Command line summary

3.4.3 Running STM32CubeMX plug-in from Eclipse IDE

  1. Launch Eclipse environment.
  2. Once Eclipse IDE is open, click open new perspective:
  3. Select STM32CubeMX to open STM32CubeMX as a perspective (see Figure 9).
  4. STM32CubeMX perspective opens (see Figure 10). Enter STM32CubeMX user

interface via the Welcome menus. STM32CubeMX icon on your desktop. project for that tool chain. Table 1. Command line summary (continued)

3.5 Getting STM32Cube updates

  • Perform self-updates of STM32CubeMX and of the STM32Cube firmware packages installed on the user computer
  • Download new firmware packages and patches Installation and update related sub-menus are available under the Help menu. Off-line updates can also be performed on computers without internet access (see Figure 16). This is done by browsing the filesystem and selecting available STM32Cube firmware zip packages. If the PC on which STM32CubeMX runs is connected to a computer network using a proxy server, STM32CubeMX needs to connect to that server to access the internet, get self- updates and download firmware packages. Refer to Section 3.5.1: Updater configuration for a description of this connection configuration. To view Windows default proxy settings, select Internet options from the Control panel and select LAN settings from the Connections tab (see Figure 11).

Figure 11. Displaying Windows default proxy settings

  • Without proxy: the application directly accesses the web (Windows default configuration).
  • Proxy without login/password
  • Proxy with login/password: when using an internet browser, a dialog box opens and prompts the user to enter his login/password.
  • Web proxies with login/password: when using an internet browser, a web page opens and prompts the user to enter his login/password.
  1. Go to http://www.st.com/stm32cube and download the relevant STM32Cube firmware

package from the Associated Software section.

  1. Unzip the zip package to your STM32Cube repository. Find out the default repository

update it to use a different location or name).

3.5.1 Updater configuration

  1. Select Help > Updater Settings to open the Updater Settings window.
  2. From the Updater Settings tab (see Figure 12)

b) Enable/Disable the automatic check for updates. Figure 12. Updater Settings window

  1. In the Connection Parameters tab, specify the proxy server settings appropriate for

On Windows, proxy parameters will be retrieved from the PC system settings. login/password configuration is used. each time STM32CubeMX is launched.

  1. Click the Check Connection button to verify if the connection works. A green check

Figure 13. Connection Parameters tab - No proxy

Figure 14. Connection Parameters tab - Use System proxy parameters

Figure 15. Connection Parameters tab - Manual Configuration of Proxy Server

  1. Select Help > Install New Libraries sub-menu to select among a list of possible
  2. If the tool is configured for manual checks, select Help > Check for Updates to find out

about new tool versions or firmware library patches available to install.

3.5.2 Downloading new libraries

  1. Select Help > Install New Libraries to open the New Libraries Manager window.

on the user PC (if any), and the latest version available from http://www.st.com. ensure that it is fully supported by STM32CubeMX. available from http://www.st.com.

  1. Click the checkbox to sele ct a package then “Install Now” to start the download.

See Figure 16 for an example.

Figure 16. New library Manager window

3.5.3 Removing libraries

  1. Select Help > Install New Libraries to open the New Libraries Manager window.
  2. Click a green checkbox to select a pa ckage available in stm32cube repository.
  3. Click the Remove Now button and confirm. A progress window then opens to show the

Refer to Figure 17 to Figure 19 for an example. Figure 17. Removing libraries

Figure 18. Removing library confirmation message Figure 19. Library deletion progress window

3.5.4 Checking for updates

  1. Click the icon to open the Up date Manager window or Select Help > Check for

Updates. All the updates available for the user current installation are listed.

  1. Click the check box to select a package, and then Install Now to download the update.

4 STM32CubeMX User Interface

  1. Select the relevant IPs and their operating modes from the Pinout view.
  2. Configure the clock tree from the clock configuration view.

automatically displays more options on the Clock tree view (see Figure 23).

  1. Configure the parameters required to initialize the IP operating modes from the
  2. Generate the initialization C code.

4.1 Welcome page

Figure 20 and to Table 2 for a description of the Welcome page. Figure 20. STM32CubeMX Welcome page

4.2 New project window

  • The MCU selector tab offering a list of target processors
  • A Board selector tab showing a list of STMicroelectronics boards. The MCU selector allows filtering on various criteria: series, lines, packages, peripherals and additional MCU characteristics such as memory size or number of I/Os (see Figure 21). The Board selector allows filtering on STM32 board types, series and peripherals (see Figure 22). Only the default board configuration is proposed. Alternative board configurations obtained by reconfiguring jumpers or by using solder bridges are not supported. When a board is selected, the Pinout view is initialized with the relevant MCU part number along with the pin assignments for the LCD, buttons, communication interfaces, LEDs, etc...(see Figure 24). Optionally, the user can choose to initialize it with the default peripheral modes (see Figure 25). When a board configuration is selected, the signals change to 'pinned', i.e. they cannot be moved automatically by STM32CubeMX constraint solver (user action on the peripheral tree, such as the selection of a peripheral mode, will not move the signals). This ensures that the user configuration remains compatible with the board.

Table 2. Welcome page shortcuts configuration from the Board selector tab).

Figure 21. New Project window - MCU selector

Figure 22. New Project window - board selector

4.3 Main window

Figure 23). Refer to Section 4.3 for a detailed description of the toolbar and menus. Figure 23. STM32CubeMX Main window upon MCU selection

4.4 Toolbar and menus

  • File menu
  • Project menu
  • Pinout menu (displayed only when the Pinout view has been selected)
  • Window menu
  • Help menu STM32CubeMX menus and toolbars are described in the sections below.

4.4.1 File menu

Refer to Table 3 for a description of the File menu and icons. Table 3. File menu functions selecting an STM32CubeMX configuration .ioc file. when the project includes user code). as well as the import settings. configuration. Otherwise, the menu is disabled.

4.4.2 Project menu

Refer to Table 4 for a description of the Project menu and icons.

4.4.3 Pinout menu

description of the Pinout menu and icons. Figure 26. Pinout menus (Pinout tab selected) Table 4. Project menu configuration (pinout, clocks, peripherals and middleware).

  1. If the project was previously saved, the reports are generated at the same location as the project

project configuration as an .ioc file or not.

Figure 27. Pinout menus (Pinout tab not selected) Table 5. Pinout menu allowing the user to specify a label name for each pin of the list. Click the pin icon to pin/unpin signals individually. and select action to pin or unpin all selected signals at once. according to placement on MCU. the Chip view to stop blinking. instead of the names of the signals assigned to the pins. have an influence on the pinout. associated mode (highlighted in orange and not pinned). (recommended configuration to optimize power consumption). microcontroller debug facilities. among the total number of GPIO pins that are configured.

4.4.4 Window menu

The Window menu allows to access the Outputs function (see Table 6).

4.4.5 Help menu

Refer to Table 7 for a description of the Help menu and icons. or gray (when not available). Available from toolbar only. Table 5. Pinout menu (continued) Table 6. Window menu encountered upon users actions. Table 7. Help menu

4.5 Output windows

4.5.1 MCUs selection pane

peripherals, package..) when an MCU was selected last. to the new MCU. The user will be prompted to confirm this action before proceeding. Figure 28. MCU selection menu

4.5.2 Output pane

installed on you PC and up-to-date. and firmware releases will be stored.

Figure 29. Output pane

4.6 Import Project window

  • Pino ut tab: MCU pins and corresponding peripheral modes.The import fails if the same peripheral instances are not available in the target MCU.
  • Clock configuration tab: clock tree parameters.
  • Configuration tab: peripherals and middleware libraries initialization parameters.
  • Project settings: choice of toolchain and code generation options. To import a project, proceed as follows: 1. Select the Imp ort project icon that appears under the File menu after starting a New Project and once an MCU has been selected. The menu remains active as long as no use r configuration settings are defined for the new project, that is just after the MCU selection. It is disabled as soon as a user action is performed on the project configuration. 2. Select File > Imp ort Project for the dedicated Import project window to open. This window allows to specify the following options: – The STM32CubeMX configuration file (.ioc) pathname of the project to import on top of current empty project. – Whether to import the PCC configurat ion defined in the Power Consumption Calculator tab or not. – Whether to import the project settings defined through the Project > Settings menu: IDE selection, code generation options and advanced settings. – Whether to import the project settings defined through the Project > Settings menu: IDE selection and code generation options. – Whether to attempt to import the whole configuration (Automatic import) or only a subset (Manual Import). a) Automatic project import (see Figure 30)

Figure 31. Manual project import the import, the user needs to choose one.

UM1718 STM32CubeMX User Interface 230 conflicts: the Import Status window and the Peripheral list get refreshed to indicate errors, warnings and whether the import has been successful or not: – Warning icons indicate that the user has selected a peripheral instance more than once and that one of the import requests will not be performed. Figure 32 shows an example where the ADC1 instance has been selected twice. – A cross sign indicates that there is a pin out conflict and that the configuration can not be imported as such. In Figure 32, the SPI6 instance configuration can not be imported on SPI3 because it conflicts with the previously selected SPI1 configuration. The manual import can be used to refine import choices and resolve the issues raised by the import trial. Figure 33 shows how to complete the import successfully, that is, in this case, by unselecting the request for ADC2 and SPI1 imports. The Show View function allows switching between the different configuration tabs (pinout, clock tree, peripheral configuration) for checking influence of the "Try Import" action before actual deployment on current project (see Figure 33).

Figure 32. Import Project menu - Try import with errors

Figure 33. Import Project menu - Successful import after adjustments

  1. Choose OK to import with the current status or Cancel to go back to the empty project

more possible to import a non-empty configuration.

4.7 Set unused / Reset used GPIOs windows

These windows allow configuring several pins at a time in the same GPIO mode.

  • Select Pinout > Set unused GPIOs from the STM32CubeMX menu bar. Note: The user selects the number of GPIOs and lets STM32CubeMX choose the actual pins to be configured or reset, among the available ones.

Figure 34. Set unused pins window

  • Select Pinout > Reset used GPIOs from the STM32CubeMX menu bar. Depending whether the Keep Current Signals Placement option is checked or not on the toolbar, STM32CubeMX conflict solver will be able to move or not the GPIO signals to other unused GPIOs: – When Keep Current Signals Placement is off (unchecked), STM32CubeMX conflict solver can move the GPIO signals to unused pins in order to fit in another peripheral mode. – When Keep Current Signals Placement is on (checked), GPIO signals will not be moved and the number of possible peripheral modes becomes limited. Refer to Figure 36 and Figure 37 and check the limitation in available peripheral modes. Figure 35. Reset used pins window

Figure 36. Set unused GPIO pins with Keep Current Signals Placement checked

Figure 37. Set unused GPIO pins with Keep Current Signals Placement unchecked

4.8 Project Settings window

  • A general project setting tab allowing to specify the project name, the location, the toolchain, and the firmware version.
  • A code generation tab allowing to set code generation options such as the location of peripheral initialization code, library copy/link options, and to select templates for customized code.
  • An advanced settings tab dedicated to ordering STM32CubeMX initialization function calls. There are several ways to open the Project Settings window: 1. By selecting Project > Settings from the STM32CubeMX menu bar (see Figure 38). The code generation will then be generated in the project folder tree shown in Figure 39. 2. By clicking Project > Generate code for the first time. 3. By selecting Save As for a project that includes C code generation (and not only pin configuration).

Figure 38. Project Settings window

Figure 39. Project folder

4.8.1 Project tab

  • Project settings: project name, location, toolchain folder for toolchain specific generated files, and toolchain to be used for project generation. Selecting Other Toolchains (GPDSC) generates a gpdsc file. The gpdsc file provides a generic description of the project, including the list and paths of drivers and other files (such as startup files) that are required for building the project. This allows extending STM32CubeMX project generation to any toolchain supporting gpdsc since the toolchain will be able to load a STM32CubeMX generated C project by processing the gpdsc file information. To standardize the description of embedded projects, the gpdsc solution is based on CMSIS-PACK.
  • Additional project settings for SW4STM32 and Atollic TrueSTUDIO toolchains: Select the optional Generate under root checkbox to generate the toolchain project files in STM32CubeMX user project root folder or unselect it to generate them under a dedicated toolchain folder. STM32CubeMX project generation under the root folder allows to benefit from the following Eclipse features when using Eclipse-based IDEs such as SW4STM32 and TrueStudio: – Optional copy of the project into the Eclipse workspace when importing a project. – Use of source control systems such as GIT or SVN from the Eclipse workspace. However, it shall be noted that choosing to copy the project into workspace will prevent any further synchronization between changes done in Eclipse and changes done in STM32CubeMX as there will be 2 different copies of the project.
  • Linker settings: value of minimum heap and stack sizes to be allocated for the application. The default values proposed are 0x200 and 0x400 for heap and stack

UM1718 STM32CubeMX User Interface 230 sizes, respectively. These values may need to be increased when the application uses middleware stacks.

  • Firmware package selection when more than one version is available (this is the case when successive versions implement the same API and support the same MCUs). By default, the latest available version is used.

4.8.2 Code Generator tab

The Code Generator tab allows specifying the following code generation options (see Figure 40):

  • STM32Cube Firmware Library Package option
  • Generated files options
  • HAL settings options
  • Custom code template options STM32Cube Firmware Library Package option The following actions are possible:
  • Copy all used libraries into the project folder STM32CubeMX will copy to the user project folder, the drivers libraries (HAL, CMSIS)
  • Copy only the necessary library files: STM32CubeMX will copy to the user project folder only the library files relevant to the user configuration (e.g., SDIO HAL driver from the HAL library,…).
  • Add the required library as referenced in the toolchain project configuration file By default, the required library files are copied to the user project. Select this option for the configuration file to point to files in STM32CubeMX repository instead: the user project folder will not hold a copy of the library files but only a reference to the files in STM32CubeMX repository. Generated files options This area allows defining the following options:
  • Generate peripheral initialization as a pair of .c/.h files or keep all peripheral initializations in the main.c file.
  • Backup previously generated files in a backup directory The .bak extension is added to previously generated .c/.h files. Keep user code when regenerating the C code. This option applies only to user sections within STM32CubeMX generated files. It does not apply to the user files that might have been added manually or generated via ftl templates.
  • Delete previously generated files when these files are no longer needed by the current configuration. For example, uart.c/.h file are deleted if the UART peripheral, that was enabled in previous code generation, is now disabled in current configuration.

STM32CubeMX User Interface UM1718 HAL settings options This area allows selection one HAL settings options among the following:

  • Set all free pins as analog to optimize power consumption
  • Enable/disable Use the Full Assert function: the Define statement in the stm32xx_hal_conf.h configuration file will be commented or uncommented, respectively. Custom code template options To generate custom code, click the Settings button under Template Settings, to open the Template Settings window (see Figure 41). The user will then be prompted to choose a source directory to select the code templates from, and a destination directory where the corresponding code will be generated. The default source directory points to the extra_template directory, within STM32CubeMX installation folder, which is meant for storing all user defined templates. The default destination folder is located in the user project folder. STM32CubeMX will then use the selected templates to generate user custom code (see Section 5.2: Custom code generation). Figure 42 shows the result of the template configuration shown on Figure 41: a sample.h file is generated according to sample_h.ftl

Figure 40. Project Settings Code Generator

Figure 41. Template Settings window

Figure 42. Generated project template

4.8.3 Advanced Settings tab

peripheral initialization function. It is up to the user code to do it. Note: Useful tooltips are also available by ho vering the mouse over the different options.

Figure 43. Advanced Settings window

4.9 Update Manager windows

  1. Select Help > Check for updates to open the Check Update Manager window and

find out about the latest software versions available for download.

  1. Select Help > Install new libraries to open the New Libraries Manager window and

previously installed software packages.

  1. Select Help > Updater settings to open the Updater settings window and configure

repository folder where STM32Cube software packages are stored).

4.10 About window

This window displays STM32CubeMX version information. To open it, select Help > About from the STM32CubeMX menu bar. Figure 44. About window

4.11 Pinout view

peripherals/middleware and of their operating modes. activating the middleware mode. Tooltips guide the user through the configuration. user_diskio.c/.h driver files with the necessary code. its name (e.g. PC4) and its current alternate function assignment if any.

  • From the IP tree by clicking the peripheral names and selecting the operating modes (see Section 4.11.1: IP tree pane).
  • For advanced users, by clicking a pin on the Chip view to manually map it to a peripheral function (see Section 4.11.2: Chip view). In addition, selecting Pinout > Set unused GPIOs allows configuring in one shot several unused pins in a given GPIO mode. Note: The Pinout view is automatically refreshed to display the resulting pinout configuration. Pinout relevant menus and shortcuts are available when the Pinout view is active (see the menu dedicated sections for details on the Pinout menus).

Figure 45. STM32CubeMX Pinout view

4.11.1 IP tree pane

modes corresponding to the application. Table 8 shows the icons and color scheme used in the IP tree pane. Table 8. IP tree pane - icons and color scheme one of its other modes is unavailable. one of its modes is unavailable. display the tooltip describing the conflict. configuration is no longer available. mode, this peripheral is highlighted in red. dependencies when the conditions are not fulfilled.

4.11.2 Chip view

  • The MCU in a specific package (BGA, LQFP…)
  • The graphical representation of its pinout, each pin being represented with its name (e.g. PC4: pin 4 of GPIO port C) and its current function assignment (e.g. ETH_MII_RXD0) (see Figure 46 for an example). The Chip view is automatically refreshed to match the user configuration performed via the peripheral tree. It shows the pins current configuration state. Assigning pins through the Chip view instead of the peripheral pane requires a good knowledge of the MCU since each individual pin can be assigned to a specific function. Tips and tricks
  • Use the mouse wheel to zoom in and out.
  • Click and drag the chip diagram to move it. Click best fit to reset it to best suited position and size (see Table 5).
  • Use Pinout > Generic CSV pinout text file to export the pinout configuration into text format.
  • Some basic controls, such as insuring blocks of pins consistency, are built-in. See Appendix A: STM32CubeMX pin assignment rules for details.

Figure 46. Chip view

Table 9 shows the icons and color scheme used in the Chip view. Table 9. STM32CubeMX Chip view - Icons and color scheme name, Reset state or GPIO mode. Move your mouse over the pin name to display it. The alternate pins available are highlighted in blue. no alternate function is configured (pin in reset state). Click the pin name to display the list. When a function has been mapped to the pin, it is highlighted in blue.

Figure 47. Red highlights and tooltip example: no mode configuration available mode of the I2C3 peripheral. Non-configured pins are shown in gray (default state). ambiguity, the pin color switches to green. configured to achieve a valid mode configuration. ambiguity, the pins are shown in green. Table 9. STM32CubeMX Chip view - Icons and color scheme (continued)

Figure 48. Orange highlight and tooltip example: some configurations unavailable been allocated (USART3 synchronous mode). Figure 49. Tooltip example: all configurations unavailable

4.11.3 Chip view advanced actions

  1. Click the pin in the Chip view to display the list of all other possible alternate functions

together with the current assignment highlighted in blue (see Figure 50).

  1. Click to select th e new function to assign to the pin.

Figure 50. Modifying pin assignments from the Chip view

  1. Press the CTRL key and click the pin in the Chip view. Possible pins for relocation, if

any, are highlighted in blue.

  1. Drag the function to the target pin.

Caution: A pin assignment performed from the Chip view overwrites any previous assignment. remapping blocks, move the mouse over the target pin. Figure 51. Example of remapping in case of block of pins consistency tooltip describing the conflict.

UM1718 STM32CubeMX User Interface 230 If the conflict cannot be solved by remapping the modes, the user can try the following:

  • If the box is checked, try to select the peripherals in a different sequence.
  • Uncheck the Keep Current Signals Placement box and let STM32CubeMX try all the remap combinations to find a solution.
  • Manually remap a mode of a peripheral when you cannot use it because there is no pin available for one of the signals of that mode.

4.11.4 Keep Current Signals Placement

This checkbox is available from the toolbar when the Pinout view is selected (see Figure 26 and Table 5). It can be selected or unselected at any time during the configuration. It is unselected by default. It is recommended to keep the checkbox unchecked for an optimized placement of the peripherals (maximum number of peripherals concurrently used). The Keep Current Signals Placement checkbox should be selected when the objective is to match a board design. Keep Current Signals Placement is unchecked This allows STM32CubeMX to remap previously mapped blocks to other pins in order to serve a new request (selection of a new IP mode or a new IP mode function) which conflicts with the current pinout configuration. Keep Current Signals Placement is checked This ensures that all the functions corresponding to a given peripheral mode remain allocated (mapped) to a given pin. Once the allocation is done, STM32CubeMX cannot move a peripheral mode function from one pin to another. New configuration requests are served if it is feasible within current pin configuration. This functionality is useful to:

  • Lock all the pins corresponding to peripherals that have been configured using the Peripherals panel.
  • Maintain a function mapped to a pin while doing manual remapping from the Chip view. Tip If a mode becomes unavailable (highlighted in red), try to find another pin remapping configuration for this mode by following the steps below: 1. From the Chip view, unselect the assigned functions one by one until the mode becomes available again. 2. Then, select the mode again and conti nue the pinout configuration with the new sequence (see Appendix A: STM32CubeMX pin assignment rules for a remapping example). This operation being time consuming, it is recommended to unselect the Keep Current Signals Placement checkbox. Note: Even if Keep Current Signals placemen t is unchecked, GPIO_ functions (excepted GPIO_EXTI functions) are not moved by STM32CubeMX.

STM32CubeMX User Interface UM1718

4.11.5 Pinning and labe ling signals on pins

STM32CubeMX comes with a feature allowing the user to selectively lock (or pin) signals to pins: This will prevent STM32CubeMX from automatically moving the pinned signals to other pins when resolving conflicts.There is also the possibility to label the signals: User labels are used for code generation (see Section 5.1 for details). STM32CubeMX comes with a feature allowing the user to selectively lock (or pin) signals to pins. This prevents STM32CubeMX from automatically moving pinned signals to other pins when resolving conflicts. Labels, that are used for code generation, can also be assigned to the signals (see Section 5.1 for details). There are several ways to pin, unpin and label the signals: 1. From the Chip view, right-click a pin with a signal assignment. This opens a contextual menu: a) For unpinned signals, select Signal Pinning to pin the signal. A pin icon is then displayed on the relevant pin. The signal can no longer be moved automatically (for example when resolving pin assignment conflicts). b) For pinned signals, select Signal Unpinning to unpin the signal. The pin icon is removed. From now on, to resolve a conflict (such as peripheral mode conflict), this signal can be moved to another pin, provided the Keep user placement option is unchecked. c) Select Enter User Label to specify a user defined label for this signal. The new label will replacing the default signal name in the Chip view. 2. From the pinout menu, select Pins/Signals Options The Pins/Signals Options window (see Figure 52) lists all configured pins. a) Click the first column to individually pin/unpin signals. b) Select multiple rows and right-click to open the contextual menu and select Signal(s) Pinning or Unpinning.

Figure 52. Pins/Signals Options window c) Select the User Label field to edit the field and enter a user-defined label. d) Order list alphabetically by Pin or Sign al name by clicking the column header.

4.11.6 Setting HAL timebase source

ARM-Cortex system timer (SysTick). configuration (tick and priority) and most RTOSs force the SysTick priority to be the lowest. Service Request context (no dead lock issue). select a clock among the available clock sources: SysTick, TIM1, TIM2,... (see Figure 53).

use of FreeRTOS influence the generated code. Figure 55. NVIC settings when using systick as HAL timebase, no FreeRTOS

  • main.c file /* SysTick_IRQn interrupt configuration */ HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
  • stm32f4xx_it.c file /** * @brief This function handles System tick timer. void SysTick_Handler(void) /* USER CODE BEGIN SysTick_IRQn 0 */

Figure 56. NVIC settings when using FreeRTOS and SysTick as HAL timebase

UM1718 STM32CubeMX User Interface 230 As shown in the code snippets given below, the SysTick interrupt handler is updated to use CMSIS-os osSystickHandler function.

  • main.c file /* SysTick_IRQn interrupt configuration */ HAL_NVIC_SetPriority(SysTick_IRQn, 15, 0);
  • stm32f4xx_it.c file /** * @brief This function handles System tick timer. void SysTick_Handler(void) /* USER CODE BEGIN SysTick_IRQn 0 */ /* USER CODE END SysTick_IRQn 0 */ HAL_IncTick(); osSystickHandler(); /* USER CODE BEGIN SysTick_IRQn 1 */ /* USER CODE END SysTick_IRQn 1 */

function that configures the TIM2 as the HAL time-base source. (Low) if FreeRTOS is used, otherwise it is set to 0 (High). Figure 57. NVIC settings when using freeRTOS and TIM2 as HAL timebase

  • SysTick_Handler calls osSystickHandler when FreeRTOS is used, otherwise it calls HAL_SYSTICK_IRQHandler.
  • TIM2_IRQHandler is generated to handle TIM2 global interrupt.

4.12 Configuration view

  • Green checkmark: correct configuration
  • Warning sign: incomplete but still functional configuration
  • Red cross: for invalid configuration. Note: GPIO and Peripheral modes that influence the pinout can be set only from the Pinout view. They are read-only in the Configuration view. In this view, the MCU is shown on the left pane by its IP tree and on the right pane, by the list of IPs organized in Middleware, Multimedia, Connectivity, Analog, System and Control categories. Each peripheral instance has a dedicated button to edit its configuration: as an example, TIM1 and TIM3 TIM instances are shown as dedicated buttons in Figure 58.

Figure 58. STM32CubeMX Configuration view

or via a tab in the other configuration windows of the IPs which use them (see Figure 59). Figure 59. Configuration window tabs for GPIO, DMA and NVIC settings (STM32F4 series) Table 10. IP configuration buttons Badly configured with some wrong parameter values. Click to display the errors highlighted in red.

4.12.1 IP and Middleware Configuration window

Configuration windows example.

  • Parameter settings to configure library dedicated parameters for the selected peripheral or middleware,
  • NVIC, GPIO and DMA settings to set the parameters for the selected peripheral (see Section 4.12.5: NVIC Configuration window, Section 4.12.3: GPIO Configuration window and Section 4.12.4: DMA Configuration windowfor configuration details).
  • User constants to create one or several user defined constants, common to the whole project (see Section 4.12.2: User Constants configuration window for user constants details). Invalid settings are detected and are either:
  • Reset to minimum valid value if user choice was smaller than minimum threshold,
  • Reset to maximum valid value if user choice was greater than maximum threshold,
  • Reset to previous valid value if previous value was neither a maximum nor a minimum threshold value,
  • Highlighted in red: Table 11 describes IP and middleware configuration buttons and messages.

Figure 60. IP Configuration window (STM32F4 series)

Table 11. IP Configuration window buttons and tooltips

4.12.2 User Constants configuration window

Figure 61. User Constants window Figure 62. Extract of the generated mxconstants.h file

Figure 63. Using constants for peripheral parameter settings

  • A name that must comply with the following rules: – It must be unique. – It shall not be a C/C++ keyword. – It shall not contain a space. – It shall not start with digits.
  • A value The constant value can be: (see Figure 61 for examples): – a simple decimal or hexadecimal value – a previously defined constant – a formula using arithmetic operators (subtr action, addition, division, multiplication, and remainder) and numeric value or user-defined numeric constants as operands. – a character string: the string value mu st be between double quotes (example: “constant_for_usart”).

4.12.3 GPIO Configuration window

internal pull-up whenever needed. window in the IP instance configuration window. code will be updated accordingly. Figure 70. GPIO Configuration window - GPIO selection

4.12.4 DMA Configuration window

Click DMA in the Configuration pane to open the DMA configuration window. CPU is running, and memory to memory transfers (if supported). default or via the IP configuration window. requests to be mapped to peripherals signals (see Figure 74). Figure 74. Adding a new DMA request to fully describe the DMA transfer run-time parameters such as the start address, etc.... used to decide which stream to select for the next DMA transfer. equal software priorities, a hardware priority that is given by the stream number.

Figure 75. DMA Configuration

  • Mode: regular mode, circular mode, or peripheral flow controller mode (only available for the SDIO IP).
  • Increment Add: the type of peripheral address and memory address increment (fixed or post-incremented in which case the address is incremented after each transfer). Click the checkbox to enable the post-incremented mode.
  • Peripheral data width: 8, 16 or 32 bits
  • Switching from the default direct mode to the FIFO mode with programmable threshold: a) Click the Use FIFO checkbox. b) Then, configure the peripheral and memory data width (8, 16 or 32 bits). c) Select between single transfer and burst transfer. If you select burst transfer, choose a burst size (1, 4, 8 or 16). In case of memory-to-memory transfer (MemtoMem), the DMA configuration applies to a source memory and a destination memory.

Figure 76. DMA MemToMem configuration

4.12.5 NVIC Configuration window

configuration window (see Figure 77).

  • The NVIC tab allows enabling peripheral interrupts in the NVIC controller and setting their priorities.
  • The Code generation tab allows selecting options for interrupt related code generation. Enabling interruptions using the NVIC tab view The NVIC view (see Figure 77) does not show all possible interrupts but only the ones available for the IPs selected in the Pinout and Configuration panes. System interrupts are displayed but can never be disabled. Check/Uncheck the Show only enabled interrupts box to filter or not enabled interrupts. Use the search field to filter out the interrupt vector table according to a string value. As an example, after enabling UART IPs from the Pinout pane, type UART in the NVIC search field and click the green arrow close to it: all UART interrupts are then displayed. Enabling a peripheral interrupt will generate of NVIC function calls HAL_NVIC_SetPriority and HAL_NVIC_EnableIRQ for this peripheral.

STM32CubeMX User Interface UM1718 STM32CubeMX NVIC configuration consists in selecting a priority group, enabling/disabling interrupts and configuring interrupts priority levels (preemption and sub-priority levels): 1. Select a priority group Several bits allow to define NVIC priority levels. These bits are divided in two priority groups corresponding to two priority types: preemption priority and sub-priority. For example, in the case of STM32F4 MCUs, the NVIC priority group 0 corresponds to 0- bit preemption and 4-bit sub-priority. 2. In the interrupt table, click one or more rows to select one or more interrupt vectors. Use the widgets below the interrupt table to configure the vectors one by one or several at a time: – Enable checkbox: check/uncheck to enable/disable the interrupt. – Preemption priority: select a priority level. The preemption priority defines the ability of one interrupt to interrupt another. – Sub-priority: select a priority level. The sub-priority defines the interrupt priority level. – Click Apply to save changes, and OK to close the window. Code generation options for interrupt handling The Code Generation view allows customizing the code generated for interrupt initialization and interrupt handlers:

  • Selection/Unselection of all interrupts for sequence ordering and IRQ handler code generation Use the checkboxes in front of the column names to configure all interrupts at a time (see Figure 80). Note that system interrupts are not eligible for init sequence reordering as the software solution does not control it.

Figure 80. NVIC Code generation – All interrupts enabled

  • Default initialization sequence of interrupts By default, the interrupts are enabled as part of the peripheral MSP initialization function, after the configuration of the GPIOs and the enabling of the peripheral clock. This is shown in the CAN example below, where HAL_NVIC_SetPriority and HAL_NVIC_EnableIRQ functions are called within stm32xxx_hal_msp.c file inside the peripheral msp_init function. Interrupt enabling code is shown in green. void HAL_CAN_MspInit(CAN_HandleTypeDef* hcan) GPIO_InitTypeDef GPIO_InitStruct; if(hcan->Instance==CAN1) /* Peripheral clock enable */ __CAN1_CLK_ENABLE(); /**CAN1 GPIO Configuration

STM32CubeMX User Interface UM1718 GPIO_InitStruct.Pin = GPIO_PIN_0|GPIO_PIN_1; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF9_CAN1; HAL_GPIO_Init(GPIOD, &GPIO_InitStruct); /* Peripheral interrupt init */ HAL_NVIC_SetPriority(CAN1_TX_IRQn, 2, 2); HAL_NVIC_EnableIRQ(CAN1_TX_IRQn); For EXTI GPIOs only, interrupts are enabled within the MX_GPIO_Init function: /*Configure GPIO pin : MEMS_INT2_Pin */ GPIO_InitStruct.Pin = MEMS_INT2_Pin; GPIO_InitStruct.Mode = GPIO_MODE_EVT_RISING; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(MEMS_INT2_GPIO_Port, &GPIO_InitStruct); /* EXTI interrupt init*/ HAL_NVIC_SetPriority(EXTI15_10_IRQn, 0, 0); HAL_NVIC_EnableIRQ(EXTI15_10_IRQn); For some peripherals, the application still needs to call another function to actually activate the interruptions. Taking the timer peripheral as an example, the function HAL_TIM_IC_Start_IT needs to be called to start the Timer input capture (IC) measurement in interrupt mode.

  • Configuration of interrupts initialization sequence Checking Select for Init sequence ordering for a set of peripherals moves the HAL_NVIC function calls for each peripheral to a same dedicated function, named MX_NVIC_Init, defined in the main.c. Moreover, the HAL_NVIC functions for each peripheral are called in the order specified in the Code generation view bottom part (see Figure 81). As an example, the configuration shown in Figure 81 generates the following code: /** NVIC Configuration void MX_NVIC_Init(void) /* CAN1_TX_IRQn interrupt configuration */ HAL_NVIC_SetPriority(CAN1_TX_IRQn, 2, 2); HAL_NVIC_EnableIRQ(CAN1_TX_IRQn); /* PVD_IRQn interrupt configuration */ HAL_NVIC_SetPriority(PVD_IRQn, 0, 0);

Figure 81. NVIC Code generation – Interrupt initialization sequence configuration

  • Interrupts handler code generation

By default, STM32CubeMX generates interrupt handlers within the stm32xxx_it.c file. mentioned earlier from the stm32xxx_it.c file. Figure 82. NVIC Code generation – IRQ Handler generation

4.12.6 FreeRTOS middlewar e configuration view

resources required for a real-time OS application and reserve the corresponding heap.

  1. In the Configuration tab, enable FreeRTOS from the tree view.
  2. Click FreeRTOS in the Configuration pane to open the FreeRTOS configuration

parameters and objects, such as tasks, timers, queues, and semaphores. The Config parameters values allow configuring Kernel and Software settings. application and thus optimizing the code size. Both Config and Include parameters will be part of the FreeRTOSConfig.h file. Figure 83. FreeRTOS configuration view

(see Figure 40: Project Settings Code Generator). Figure 84. FreeRTOS: configuring tasks and queues

  • Tasks Under the Tasks section, click the Add button to open the New Task window where task name, priority, stack size and entry function can be configured (see Figure 85). These settings can be updated at any time: double-clicking a task row opens again the new task window for editing. The entry function can be generated as weak or external: – When the task is generated as weak, the user can propose another definition than the one generated by default. – When the task is extern, it is up to the user to provide its function definition. By default, the function definition is generated including user sections to allow customization.
  • Queues Under the Queues section, click the Add button to open the New Queue window where the queue name, size and item size can be configured (see Figure 85). The queue size corresponds to the maximum number of items that the queue can hold at a
  • 1 byte for uint8_t, int8_t, char and portCHAR types
  • 2 bytes for uint16_t, int16_t, short and portSHORT types
  • 4 bytes for uint32_t, int32_t, int, long and float
  • 8 bytes for uint64_t, int64_t and double A default value of 4 bytes will be used when the item size can not be automatically derived from user input. These settings can be updated at any time: double-clicking a queue row opens again the new queue window for editing.

Figure 85. FreeRTOS: creating a new task FreeRTOS: configuring tasks and queues.

and Semaphores tab (see Figure 86). <object> window for edition. Note: Expand the window if the newly created objects are not visible. Figure 86. FreeRTOS - Configuring timers, mutexes and semaphores

UM1718 STM32CubeMX User Interface 230

  • Timers Prior to creating timers, their usage (USE_TIMERS definition) must be enabled in the software timer definitions section of the Configuration parameters tab. In the same section, timer task priority, queue length and stack depth can be also configured. The timer can be created to be one-shot (run once) or auto-reload (periodic). The timer name and the corresponding callback function name must be specified. It is up to the user to fill the callback function code and to specify the timer period (time between the timer being started and its callback function being executed) when calling the CMSIS- RTOS osTimerStart function.
  • Mutexes/Semaphores Prior to creating mutexes, recursive mutexes and counting semaphores, their usage (USE_ MUTEXES, USE_RECURSIVE_MUTEXES, USE_COUNTING_SEMAPHORES definitions) must be enabled within the Kernel settings section of the Configuration parameters tab. The following code snippet shows the generated code corresponding to Figure 86: FreeRTOS - Configuring timers, mutexes and semaphores). /* Create the semaphores(s) */ /* definition and creation of myBinarySem01 */ osSemaphoreDef(myBinarySem01); myBinarySem01Handle = osSemaphoreCreate(osSemaphore(myBinarySem01), 1); /* definition and creation of myCountingSem01 */ osSemaphoreDef(myCountingSem01); myCountingSem01Handle = osSemaphoreCreate(osSemaphore(myCountingSem01), 7); /* Create the timer(s) */ /* definition and creation of myTimer01 */ osTimerDef(myTimer01, Callback01); myTimer01Handle = osTimerCreate(osTimer(myTimer01), osTimerPeriodic, NULL); /* definition and creation of myTimer02 */ osTimerDef(myTimer02, Callback02); myTimer02Handle = osTimerCreate(osTimer(myTimer02), osTimerOnce, NULL); /* Create the mutex(es) */ /* definition and creation of myMutex01 */ osMutexDef(myMutex01); myMutex01Handle = osMutexCreate(osMutex(myMutex01)); /* Create the recursive mutex(es) */ /* definition and creation of myRecursiveMutex01 */ osMutexDef(myRecursiveMutex01);

cross appears on the tab (see Figure 87). Figure 87. FreeRTOS Heap usage

UM1718 STM32CubeMX User Interface 230

4.13 Clock tree configuration view

STM32CubeMX Clock configuration window (see Figure 88) provides a schematic overview of the clock paths, clock sources, dividers, and multipliers. Drop-down menus and buttons allow modifying the actual clock tree configuration to meet user application requirements. Actual clock speeds are displayed and active. The clock signals that are used are highlighted in blue. Out-of-range configured values are highlighted in red to flag potential issues. A solver feature is proposed to automatically resolve such configuration issues (see Figure 89). Reverse path is supported: just enter the required clock speed in the blue filed and STM32CubeMX will attempt to reconfigure multipliers and dividers to provide the requested value. The resulting clock value can then be locked by right clicking the field to prevent modifications. STM32CubeMX generates the corresponding initialization code:

  • main.c with relevant HAL_RCC structure initializations and function calls
  • stm32xxxx_hal_conf.h for oscillator frequencies and VDD values.

4.13.1 Clock tree conf iguration functions

When external clock sources are used, the user must previously enable them from the Pinout view available under the RCC peripheral. Peripheral clock configuration options Some other paths, corresponding to clock peripherals, are grayed out. To become active, the peripheral must be properly configured in the Pinout view (e.g. USB). This view allows to:

  • Enter a frequency value for the CPU Clock (HCLK), buses or peripheral clocks STM32CubeMX tries to propose a clock tree configuration that reaches the desired frequency while adjusting prescalers and dividers and taking into account other peripheral constraints (such as USB clock minimum value). If no solution can be found,

STM32CubeMX User Interface UM1718 STM32CubeMX proposes to switch to a different clock source or can even conclude that no solution matches the desired frequency.

  • Lock the frequency fields for which the current value should be preserved Right click a frequency field and select Lock to preserve the value currently assigned when STM32CubeMX will search for a new clock configuration solution. The user can unlock the locked frequency fields when the preservation is no longer necessary.
  • Select the clock source that will drive the system clock (SYSCLK) – External oscillator clock (HSE) for a user defined frequency. – Internal oscillator clock (HSI) for the defined fixed frequency. – Main PLL clock
  • Select secondary sources (as available for the product) – Low-speed internal (LSI) or external (LSE) clock – I2S input clock
  • Select prescalers, dividers and multipliers values.
  • Enable the Clock Security system (CSS) on HSE when it is supported by the MCU This feature is available only when the HSE clock is used as the system clock source directly or indirectly through the PLL. It allows detecting HSE failure and inform the software about it, thus allowing the MCU to perform rescue operations.
  • Enable the CSS on LSE when it is supported by the MCU This feature is available only when the LSE and LSI are enabled and after the RTC or LCD clock sources have been selected to be either LSE or LSI.
  • Reset the Clock tree default settings by using the toolbar Reset button ( ): This feature reloads STM32CubeMX default clock tree configuration.
  • Undo/Redo user configuration steps by using the toolbar Undo/Redo buttons ( )
  • Detect and resolve configuration issues Erroneous clock tree configurations are detected prior to code generation. Errors are highlighted in red and the Clock Configuration view is marked with a red cross (see Figure 89). Issues can be resolved manually or automatically by clicking the Resolve Clock Issue button ( ) which is enabled only if issues have been detected. The underlying resolution process follows a specific sequence: a) Setting HSE frequency to its maximum value (optional). b) Setting HCLK frequency then peripheral frequencies to a maximum or minimum value (optional). c) Changing multiplexers inputs (optional). d) Finally, iterating through multiplier/dividers values to fix the issue. The clock tree is cleared from red highlights if a solution is found. Otherwise an error message is displayed. Note: To be available from the clock tree, external clocks, I2S input clock, and master clocks shall be enabled in RCC configuration in the Pinout view. This information is also available as tooltips.

UM1718 STM32CubeMX User Interface 230 The tool will automatically perform the following operations:

  • Adjust bus frequencies, timers, peripherals and master output clocks according to user selection of clock sources, clock frequencies and prescalers/multipliers/dividers values.
  • Check the validity of user settings.
  • Highlight invalid settings in red and provide tooltips to guide the user to achieve a valid configuration. The Clock tree view is adjusted according to the RCC settings (configured in RCC IP pinout and configuration views) and vice versa:
  • If in RCC Pinout view, the external and output clocks are enabled, they become configurable in the clock tree view.
  • If in RCC Configuration view, the Timer prescaler is enabled, the choice of Timer clocks multipliers will be adjusted. Conversely, the clock tree configuration may affect some RCC parameters in the configuration view:
  • Flash latency: number of wait states automatically derived from VDD voltage, HCLK frequency, and power over-drive state.
  • Power regulator voltage scale: automatically derived from HCLK frequency.
  • Power over-drive is enabled automatically according to HCLK frequency. When the power drive is enabled, the maximum possible frequency values for AHB and APB domains are increased. They are displayed in the Clock tree view. The default optimal system settings that is used at startup are defined in the system_stm32f4xx.c file. This file is copied by STM32CubeMX from the STM32CubeF4 firmware package. The switch to user defined clock settings is done afterwards in the main function. Figure 88 gives an example of Clock tree configuration view for an STM32F429x MCU and Table 12 describes the widgets that can be used to configure each clock.

Table 12. Clock tree view widget value during clock tree configuration updates.

4.13.2 Recommendations

The Clock tree view is not the only entry for clock configuration.

  1. Go first through the RCC IP pinout configuration in the Pinout view to enable the

when available (see Figure 90). Figure 90. Clock tree configuration: enabling RTC, RCC Clock source

  1. Then go to the RCC IP configuration in the Configuration view. The settings defined

Figure 91. Clock tree configuration: RCC Peripheral Advanced parameters

4.13.3 STM32F43x/42x pow er-over drive feature

supply voltage is applied (e.g VDD > 2.1 V). availability in STM32CubeMX user interface.

Table 14 gives the relations between power-over drive mode and HCLK frequency. Table 13. Voltage scaling versus power over-drive and HCLK frequency power over-drive (see Table 14).

168 MHz for HCLK when power over-drive

Table 14. Relations between power over-drive and HCLK frequency

4.13.4 Clock tree glossary

4.14 Power Consumption Calculator (PCC) view

  • Average current consumption Power consumption values can either be taken from the datasheet or interpolated from a user specified bus or core frequency.
  • Battery life
  • Average DMIPs DMIPs values are directly taken from the MCU datasheet and are neither interpolated nor extrapolated.
  • Maximum ambient temperature (TAMAX) According to the chip internal power consumption, the package type and a maximum junction temperature of 105 °C, the tool computes the maximum ambient temperature to ensure good operating conditions. Current T AMAX implementation does not account for I/O consumption. For an accurate TAMAX estimate, I/O consumption must be specified using the Additional Consumption field. The formula for I/O dynamic current consumption is specified in the microcontroller datasheet.

Table 15. Glossary HSE High Speed External oscillator: requires an external clock circuit. PLL Phase Locked Loop: used to multiply above clock sources. LSE Low Speed External clock: powered by an external clock.

  • Make use of low power modes when any available
  • Adjust clock sources and frequencies based on the step requirements.
  • Enable the peripherals necessary for each phase. For each step, the user can choose VBUS as possible power source instead of the battery. This will impact the battery life estimation. If power consumption measurements are available at different voltage levels, STM32CubeMX will also propose a choice of voltage values (see Figure 96). An additional option, the transition checker, is available for STM32L0, STM32L1 and STM32L4 series. When it is enabled, the transition checker detects invalid transitions within the currently configured sequence. It ensures that only possible transitions are proposed to the user when a new step is added.

4.14.1 Building a power consumption sequence

The default starting view is shown in Figure 92. Figure 92. Power Consumption Calculator default view

From this view and when multiple choices are available, the user must select a VDD value. consumption sequence is configured. matches his application (see Figure 93). Figure 93. Battery selection

Figure 96. Power consumption sequence: new step default view

Figure 100. Transition checker option -show log

UM1718 STM32CubeMX User Interface 230

4.14.2 Configuring a step in the power sequence

The step configuration is performed from the Edit Step and New Step windows. The graphical interface guides the user by forcing a predefined order for setting parameters. Their naming may differ according to the selected MCU series. For details on each parameter, refer to Section 4.14.4: Power sequence step parameters glossary glossary and to Appendix D: STM32 microcontrollers power consumption parameters or to the electrical characteristics section of the MCU datasheet. The parameters are set automatically by the tool when there is only one possible value (in this case, the parameter cannot be modified and is grayed out). The tool proposes only the configuration choices relevant to the selected MCU. Proceed as follow to configure a new step: 1. Click Add or Duplicate to open the New step window or double-click a step from the sequence table to open the Edit step window. 2. Within the open step window, select in the following order: –T h e Power Mode Changing the Power Mode resets the whole step configuration. –T h e Peripherals Peripherals can be selected/unselected at any time after the Power Mode is configured. –T h e Power scale The power scale corresponds to the power consumption range (STM32L1) or the power scale (STM32F4). Changing the Power Mode or the Power Consumption Range discards all subsequent configurations. –T h e Memory Fetch Type –T h e V DD value if multiple choices available – The voltage source (battery or VBUS) –A Clock Configuration Changing the Clock Configuration resets the frequency choices further down. – When multiple choices are available, the CPU Frequency (STM32F4) and the AHB Bus Frequency/CPU Frequency(STM32L1) or, for active modes, a user specified frequency. In this case, the consumption value will be interpolated (see Section : Using interpolation). 3. Optionally set –A step duration (1 ms is the default value) –A n additional consumption value (expressed in mA) to reflect, for example, external components used by the application (external regulator, external pull-up, LEDs or other displays). This value added to the microcontroller power consumption will impact the step overall power consumption. 4. Once the configuration is complete, the Add button becomes active. Click it to create the step and add it to the sequence table.

selecting CPU frequency as User Defined and entering a frequency in Hz (see Figure 101). Figure 101. Interpolated Power Consumption

allows selecting all peripherals at once. removes them as contributors to the step consumption. Figure 103. PCC Step configuration windo w: ADC enabled using import pinout

4.14.3 Managing user-defined powe r sequence and reviewing results

  • The sequence table shows all steps and step parameters values. A category column indicates whether the consumption values are taken from the datasheet or are interpolated.
  • The sequence chart area shows different views of the power sequence according to a display type (e.g. plot all steps, plot low power versus run modes, ..)
  • The results summary provides the total sequence time, the maximum ambient temperature (T AMAX), plus an estimate of the average power consumption, DMIPS, and battery lifetime provided a valid battery configuration has been selected.

Figure 104. Power Consumption Calculator view after sequence building

Figure 105. Sequence table management functions

  1. Browse to select the sequence to load.
  2. Click the Comp are button
  3. Browse and select the .pcs sequence file to be compared with the current sequence. A

w window opens showing the selected sequence details.

dedicated windows (see Figure 106). the chart and Zoom reset by clicking the chart and dragging the mouse to the left. Figure 106. Power Consumption: Peripherals Consumption Chart

  • Total sequence time as the sum of the sequence steps durations.
  • Average consumption as the sum of each step consumption weighed by the step duration.
  • The average DMIPS (Dhrystone Million Instructions per Second) based on Dhrystone benchmark, highlighting the CPU performance for the defined sequence.
  • Battery life estimation for the selected battery model, based on the average power consumption and the battery self-discharge.
  • TAMAX: highest maximum ambient temperature value encountered during the sequence.

Figure 107. Description of the Results area

4.14.4 Power sequence step parameters glossary

  • Power modes To save energy, it is recommended to switch the microcontroller operating mode from running mode, where a maximum power is required, to a low-power mode requiring limited resources.
  • VCORE range (STM32L1) or Power scale (STM32F4) These parameters are set by software to control the power supply range for digital peripherals.
  • Memory Fetch Type This field proposes the possible memory locations for application C code execution. It can be either RAM, FLASH or FLASH with ART ON or OFF (only for families that feature a proprietary Adaptive real-time (ART) memory accelerator which increases the program execution speed when executing from Flash memory).

UM1718 STM32CubeMX User Interface 230 The performance achieved thanks to the ART accelerator is equivalent to 0 wait state program execution from Flash memory. In terms of power consumption, it is equivalent to program execution from RAM. In addition, STM32CubeMX uses the same selection choice to cover both settings, RAM and Flash with ART ON.

  • Clock Configuration This operation sets the AHB bus frequency or the CPU frequency that will be used for computing the microcontroller power consumption. When there is only one possible choice, the frequencies are automatically configured. The clock configuration drop-down list allows to configure the application clocks: – The internal or extern al oscillator sources: MSI, HSI, LSI, HSE or LSE), – The oscillator frequency, – Other determining parameters: PLL ON, LSE Bypass, AHB prescaler value, LCD with duty...
  • Peripherals The peripheral list shows the peripherals available for the selected power mode. The power consumption is given assuming that peripherals are only clocked (e.g. not in use by a running program). Each peripheral can be enabled or disabled. Peripherals individual power consumptions are displayed in a tooltip. An overall consumption due to peripheral analog and digital parts is provided in the step Results area (see Figure 108). The user can select the peripherals relevant for the application: – None ( Disable All), – Some (using IP individual checkbox), – All ( Activate All), – Or all from the previously defined pinout configuration ( Import Pinout). Only the selected and enabled peripherals are taken into account when computing the power consumption.

Figure 108. Peripheral power consumption tooltip

  • Step duration The user can change the default step duration value. When building a sequence, the user can either create steps according to the application actual power sequence or define them as a percentage spent in each mode. For example, if an application spends 30% in Run mode, 20% in Sleep and 50% in Stop, the user must configure a 3- step sequence consisting in 30 ms in Run, 20 ms in Sleep and 50 ms in Stop.
  • Additional Consumption This field allows entering an additional consumption resulting from specific user configuration (e.g. MCU providing power supply to other connected devices).

UM1718 STM32CubeMX User Interface 230

4.14.5 Battery glossary

  • Capacity (mAh) Amount of energy that can be delivered in a single battery discharge.
  • Self-discharge (%/month) This percentage, over a specified period, represents the loss of battery capacity when the battery is not used (open-circuit conditions), as a result of internal leakage.
  • Nominal voltage (V) Voltage supplied by a fully charged battery.
  • Max. Continuous Current (mA) This current corresponds to the maximum current that can be delivered during the battery lifetime period without damaging the battery.
  • Max. Pulse Current (mA) This is the maximum pulse current that can be delivered exceptionally, for instance when the application is switched on during the starting phase.

STM32CubeMX C Code generation overview UM1718

5 STM32CubeMX C Code generation overview

Refer to Section 4.4.2: Project menu for code generation and C project settings related topics.

5.1 Standard STM32Cube code generation

During the C code generation process, STM32CubeMX performs the following actions: 1. If it is missing, it down loads the relevant STM32Cube firmware 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 IP 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 IPs. Defining and calling, for each configured IP, an IP initialization function that defines a handle structure that will be passed to the corresponding IP HAL init function which in turn will call the IP HAL MSP initialization function. Note that when LwIP (respectively USB) middleware is used, the initialization C code for the underlying Ethernet (respectively USB IP) is moved from main.c to LwIP (respectively USB) initialization C code itself. – mxconstants.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 109 and Figure 110 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

STM32CubeMX C Code generation overview UM1718 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 will be automatically 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.

UM1718 STM32CubeMX C Code generation overview 230

5.2 Custom code generation

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

5.2.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 112: extra_templates folder – default content). STM32CubeMX will also generate user-specific code if any is available within the template. As shown in the below example, 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")]

5.2.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 his project via the Template Settings window accessible from the Project Settings menu (see Section 4.8: Project Settings window)

5.2.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 113:

Figure 116. Custom folder with corresponding custom generated files

6 Tutorial 1: From pinout to project C code generation

example a simple LED toggling application running on the STM32F4DISCOVERY board.

6.1 Creating a new STM32CubeMX Project

  1. Select File > New project from the main menu bar or New project from the Welcome
  2. Select the MCU Selector tab and filter down the STM32 portfolio by selecting STM32F4

as 'Series', STM32F407 as 'Lines', and LQFP100 as 'Package’ (see Figure 117).

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

Figure 117. MCU selection

Figure 119. Pinout view without MCUs selection window

6.2 Configuring the MCU pinout

  1. By default, STM32CubeMX shows the Pinout view.

e that accommodates the maximum number of peripheral modes. allocation (mapping) to a given pin. tool or when loading another project.

  1. Select the required peripherals and peripheral modes:

Figure 120. GPIO pin configuration Figure 121. Timer configuration

clock source (see Figure 122). This completes the pinout configuration for this example. Figure 122. Simple pinout configuration loading ST Discovery board configuration from the Board selector tab.

6.3 Saving the project

When saving for the first time, select a destina tion folder and filename for the project. Figure 123. Save Project As window to save the project under a different name or location.

6.4 Generating the report

to generate .pdf and .txt reports. is then generated for the project along with a .pdf and .txt reports with the same name. Answering “No” will require to provide a name and location for the report only. Figure 124. Generate Project Report - New project creation Figure 125. Generate Project Report - Project successfully created

  1. Open the .pdf report using Adobe Reader or the .txt report using your favorite text

6.5 Configuring the MCU Clock tree

and highlighted in red through a dynamic validation of minimum and maximum conditions. parameters (e.g. UART baudrate limitation). (HSE, HSI and External clock values expressed in Hertz).

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

source, and optionally by using the PLL, prescalers and multipliers. Figure 126. Clock tree view

UM1718 Tutorial 1: From pinout to project C code generation using an STM32F4 MCU 230 3. Keep the core and peripheral clocks to 16 MHz using HSI, no PLL and no prescaling. Note: Optionally, further adjust the system and pe rip heral clocks using PLL, prescalers and multipliers: Other clock sources independent from the system clock can be configured as follows: – USB OTG FS, Random Number Generator and SDIO clocks are driven by an inde pendent output of the PLL. – I2S peripherals come with their own intern al 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 allo w to output two clocks to the external circuit. 5. Click to save the project. 6. Go to the Conf iguration tab to proceed with the project configuration.

6.6 Configuring the MCU initialization parameters

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

6.6.1 Initial conditions

Select the Configuration tab to display the configuration view (see Figure 131). Peripherals and middleware modes without influence on the pinout can be disabled or enabled in the IP Tree pane. The modes that impact the pin assignments can only be selected through the Pinout tab. In the main panel, tooltips and warning messages are displayed when peripherals are not p roperly configured (see Section 4: STM32CubeMX User Interface for details). Note: The RC C peripheral initialization will use the parameter configuration done in this view as well as the configuration done in the Clock tree view (clock source, frequencies, prescaler values, etc…).

Figure 131. Configuration view

6.6.2 Configuring the peripherals

Each peripheral instance corresponds to a dedicated button in the main panel. Figure 132. Case of IP without configuration parameters

  1. Click the peripheral butt on to open the corresponding configuration window.

a) Click TIM3 to open the timer configuration window. Figure 133. Timer 3 configuration window

counter period to 1000 to make the LED blink every millisecond. Figure 134. Timer 3 configuration

  1. Optionally and when available, select:

transfers for this peripheral. unchanged. The interrupt is enabled as shown in Figure 135. –T h e User Constants tab to specify constants to be used in the project.

  1. Modify and click Apply or OK to save your modifications.

Figure 135. Enabling Timer 3 interrupt

6.6.3 Configuring the GPIOs

indicates the configuration status. Figure 136. GPIO configuration color scheme and tooltip

  1. Click the GPIO button in the Configuration view to open the Pin Configuration
  2. The first tab shows the pins that have been assigned a GPIO mode but not for a

dedicated IP. Select a Pin Name to open the configuration for that pin. the STM32F4DISCOVERY LED (see Figure 137).

Figure 137. GPIO mode configuration

  1. Click Apply then Ok to close the window.

6.6.4 Configuring the DMAs

This is not required for the example taken for the tutorial. window provides a fast and easy way to configure the DMAs (see Figure 138).

  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.

Figure 138. DMA Parameters configuration window

6.6.5 Configuring the middleware

This is not required for the example taken for the tutorial. Figure 139. FatFs disabled

  1. FatFs and USB using default settings are already marked as configured

them by following the guidelines provided at the bottom of the window. Figure 143. FatFs IP instances

  1. FatFs define statements

6.7 Generating a complete C project

6.7.1 Setting project options

  1. Select Settings from the Project menu to open the Project settings window.
  2. Select the Project Tab and choose a Project name, location and a toolchain to

generate the project (see Figure 145). Figure 145. Project Settings and toolchain choice

  1. 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). explanation on how to download the firmware package. Figure 146. Project Settings menu - Code Generator tab

6.7.2 Downloading firmware package and generating the C code

Figure 147. Missing firmware package warning message

  1. STM32CubeMX offers to download the relevant firmware package or to go on. Click

to be copied manually to obtain a complete project. Figure 148. Error during download To solve this issue, execute the next two steps. Skip them otherwise.

  1. Select Help > Updater settings menu and adjust the connection parameters to match

Figure 149. Updater settings for download

  1. Click Check connection. The check mark turns green once the connection is
  1. 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 6.8. Figure 154. C code generation output folder

  • 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 will be lost if user sections are moved or if user sections delimiters are renamed.

6.8 Building and updating the C code project

Settings menu and clicking Generate code once again.

  1. Open the project directly in the IDE toolchain by clicking Open Project from the dialog

STM32CubeMX generated project directory (see Figure 153). Figure 155. C code generation output: Projects folder

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

Figure 156. C code generation for EWARM

  1. Select the main.c f ile to open in editor.

Figure 157. STM32CubeMX generated project open in IAR IDE

Tutorial 1: From pinout to project C code generation using an STM32F4 MCU UM1718 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 Settings is enabled.

6.9 Switching to another MCU

STM32CubeMX allows loading a project configuration on an MCU of the same series. Proceed as follows: 1. Select File > Ne w Project. 2. Select an MCU belonging to the same series. As an example, you can select the STM3 2F429ZITx that is the core MCU of the 32F429IDISCOVERY board. 3. Select File > Imp ort 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 163). 4. Click the Tr y Import button and check the import status to verify if the import succeeded (see Figure 164). 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 PD1 2 and drag and drop it on PG13. 7. Select Project > Se ttings to configure the new project name and folder location. Click Generate icon to save the project and generate the code. 8. Select O pen 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.

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

the FatFs file system middleware.

  1. Select File > New Project. The Project window opens.
  2. Click the Board Selector Tab to display the list of ST boards.
  3. Select EvalBoard as type of Board and STM32F4 as series to filter down the list.
  4. Leave the option Initialize all IPs with their default mode unchecked so that the code

is generated only for the IPs used by the application.

  1. Select the STM32429I-EVAL board and click OK. The Pinout view is loaded, matching

the MCU pinout configuration on the evaluation board (see Figure 165). Figure 165. Board selection

Tutorial 2 - Example of FatFs on an SD card using STM32429I-EVAL evaluation board UM1718 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. 14. Go to the Application/User folder. Do uble click the main.c file and edit it. 15. 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 t hat an error occurred (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 th at 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. 16. 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 */ FATFS SDFatFs; /* File system object for SD card logical drive */ FIL MyFile; /* File object */ const char wtext[] = "Hello World!"; const uint8_t image1_bmp[] = { 0x42,0x4d,0x36,0x84,0x03,0x00,0x00,0x00,0x00,0x00,0x36,0x00,0x00,0x00, 0x28,0x00,0x00,0x00,0x40,0x01,0x00,0x00,0xf0,0x00,0x00,0x00,0x01,0x00, 0x18,0x00,0x00,0x00,0x00,0x00,0x00,0x84,0x03,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x29,0x74, 0x51,0x0e,0x63,0x30,0x04,0x4c,0x1d,0x0f,0x56,0x25,0x11,0x79,0x41,0x1f, 0x85,0x6f,0x25,0x79,0x7e,0x27,0x72,0x72,0x0b,0x50,0x43,0x00,0x44,0x15, 0x00,0x4b,0x0f,0x00,0x4a,0x15,0x07,0x50,0x16,0x03,0x54,0x22,0x23,0x70, 0x65,0x30,0x82,0x6d,0x0f,0x6c,0x3e,0x22,0x80,0x5d,0x23,0x8b,0x5b,0x26}; /* USER CODE END PV */ b) Insert main functi onal 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 */ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init();

UM1718 Tutorial 2 - Example of FatFs on an SD card using STM32429I-EVAL evaluation board 230 c) 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); 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*)SD_Path, 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*)SD_Path, 0, 0) != 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 { 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 */

Tutorial 2 - Example of FatFs on an SD card using STM32429I-EVAL evaluation board UM1718 HAL_GPIO_WritePin(GPIOG, GPIO_PIN_10, GPIO_PIN_RESET); while(1); } else { res = f_read(&MyFile, rtext, sizeof(wtext), &bytesread); if((strcmp(rtext,wtext)!=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); f_close(&MyFile); FATFS_UnLinkDriver(SD_Path); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1)

UM1718 Tutorial 3- Using PCC to optimize the embedded application power consumption and 230 application power consumption and more

8.1 Tutorial overview

This tutorial focuses on STM32CubeMX Power Consumption Calculator (PCC) 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 will give 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 will show how STM32CubeMX PCC feature can help to tune an application to minimize its power consumption and extend the battery life. Note: PCC 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.

Tutorial 3- Using PCC to optimize the embedded application power consumption and more

8.2 Application example description

The application is designed using the NUCLEO-L476RG board based on a 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.

8.3 Using the Power Co nsumption Calculator

8.3.1 Creating a PCC sequence

Follow the steps below to open PCC and create the sequence (see Figure 173): 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 V DD power supply. This value can be adjusted on a step by step basis (see Figure 174). b) Select the Li-MnO2 (CR2032) battery. Th is step is optional. The battery type can be changed later on (see Figure 174).

Figure 173. Power Consumption Calculation example

  1. Click the Save button to save the sequence as SequenceOne.

Figure 176. PCC sequence results before optimization

8.3.2 Optimizing appli cation power consumption

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

  • Findings All peripherals are enabled although the application requires only the RTC.
  • Actions – Lower the operating frequency. – Enable solely the RTC peripheral. – To reduce the average current consumption, reduce the time spent in this mode.
  • Results The current is reduced from 9.05 mA to 2.16 mA (see Figure 177).

Figure 177. Step 1 optimization

  • Action: Reduce the time spent in this mode to 0.1 ms.
  • 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 178).

Figure 178. Step 5 optimization

  • 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 179).

Figure 179. Step 6 optimization

  • Actions – Switch to Lower- power run mode. – Use the power-efficient LPUART peripheral. – Reduce the operating frequency to 1 MH z using the PCC interpolation feature.
  • Results The current consumption is reduced from 1.92 µA to 42 µA (see Figure 180).

Figure 180. Step 7 optimization

  • Actions: – Switch to Stop1 low-power mode. – Use the power-efficient LPUART peripheral.
  • Results The current consumption is reduced from 110 µA to 6.65 µA (see Figure 181).

Figure 181. Step 8 optimization

  • 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 182). The example given in Figure 183 shows an average current consumption reduction of 155 µA.

Figure 182. Step 10 optimization

and an average current consumption of 165.25 µA. Figure 183. PCC Sequence results after optimizations

9 FAQ

9.1 On the Pinout configurati on pane, why does STM32CubeMX

move some functions when I add a new peripheral mode? You may have unselected . In this case, the tool performs an automatic remapping to optimize your placement. 9.2 How can I manually fo rce a function remapping? You should use the Manual Remapping feature. the Chip view? Why cannot I change the function of some pins (when I click some pins, nothing happens)? These pins are specific pins (such as power supply or BOOT) which are not available as peripheral signals. ‘Java 7 update 45’ or a more recent version of the JRE? The problem generally occurs on 64-bit Windows operating system, when several versions of Java are installed on your computer and the 64-bit Java installation is too old. During STM32CubeMX installation, the computer se arches for a 64-bit installation of Java.

  • If on e is found, the ‘Java 7 update 45’ minimu m version prerequisite is checked. If the installed version is older, an error is displayed to request the upgrade.
  • If no 64-bit installation is found, STM32CubeMX searches for a 32-bit installation. If one is found and the version is too old, the ‘Java 7 update 45’ error is displayed. The user must update the installation to solve the issue. To avoid this issue from occurring, it is re commended to perform one of the following actions: 1. Remove all Java installations and reinstall only one version (32 or 64 bits) (Java 7 up date 45 or more recent). 2. Keep 32-bit and 64-bit installations but make sure that the 64-bit version is at least Java 7 up date 45. Note: Some users (Java developers for example) may need to check the PC environment variables defining hard-coded Java paths (e.g. JAVA_HOME or PATH) and update them so that they point to the latest Java installation. On Windows 7 you can check your Java installation using the Control Panel. To do this, double-c lick icon from Control Panel\\All Control Panel to open the Java settings window (see Figure 184):

Figure 184. Java Control Panel

9.5 Why does the RTC multiplexer remain inactive on the Clock

Figure 185. Pinout view - Enabling the RTC

9.6 How can I select LSE an d HSE as clock source and

view. See Figure 186 for an example. Figure 186. Pinout view - Enabling LSE and HSE clocks Figure 187. Pinout view - Setting LSE/HSE clock frequency

9.7 Why STM32CubeMX does not al low me to configure PC13,

STM32CubeMX pin assignment rules UM1718 Appendix A STM32CubeMX pin assignment rules The following pin assignment rules are implemented in STM32CubeMX:

  • Rule 1: Block consistency
  • Rule 2: Block inter-dependency
  • Rule 3: One block = one peripheral mode
  • Rule 4: Block remapping (only for STM32F10x)
  • Rule 5: Function remapping
  • Rule 6: Block shifting (only for STM32F10x)
  • Rule 7: Setting or clearing a peripheral mode
  • Rule 8: Mapping a function individually (if Keep Current Placement is unchecked)
  • Rule 9: GPIO signals mapping A.1 Block consistency When setting a pin signal (provided there is no ambiguity about the corresponding peripheral mode), all the pins/signals required for this mode are mapped and pins are shown in green (otherwise the configured pin is shown in orange). When clearing a pin signal, all the pins/signals required for this mode are unmapped simultaneously and the pins turn back to gray. Example of block mapping with a STM32F107x MCU If the user assigns I2C1_SMBA function to PB5, then STM32CubeMX configures pins and modes as follows:
  • I2C1_SCL and I2C1_SDA signals are mapped to the PB6 and PB7 pins, respectively (see Figure 188).
  • I2C1 peripheral mode is set to SMBus-Alert mode.

Figure 188. Block mapping

  • If they are unpinned, the pin configuration is reset (pin grayed out).
  • If they are pinned, the peripheral signal assigned to the pins is kept and the pins are highlighted in orange since they no longer match a peripheral mode (see Figure 189).

Figure 190. Block remapping - example 1

Figure 192. Block inter-dependency - SPI signals assigned to PB3/4/5

Figure 193. Block inter-dependency - SPI1_MISO function assigned to PA6

peripheral mode is automatically set in the Peripherals tree. SMBus-Alert mode (see Peripheral tree in Figure 194). Figure 194. One block = one peripheral mode - I2C1_SMBA function assigned to PB5 the blocks to find a solution.

to free the pins by remapping all the peripheral modes impacted by the shared pin. (shown in red) (see Figure 197). and freeing a block for the Ethernet MII mode. (see Figure 198). Figure 197. Block shifting not applied

Figure 198. Block shifting applied cleared, the corresponding pin functions are set or cleared. is unchecked and the function is not pinned (no pin icon).

UM1718 STM32CubeMX C code genera tion design choices and limitations 230 Appendix B STM32CubeMX C code generation design choices and limitations This section summarizes STM32CubeMX design choices and limitations. B.1 STM32CubeMX generated C code and user sections The C code generated by STM32CubeMX provides user sections as illustrated below. They allow user C code to be inserted and preserved at next C code generation. User sections shall neither be moved nor renamed. Only the user sections defined by STM32CubeMX are preserved. User created sections will be ignored and lost at next C code generation. /* USER CODE BEGIN 0 */ (..) /* USER CODE END 0 */ Note: STM32CubeMX may gene rate C code in some user sections. It will be up to the user to clean the parts that may become obsolete in this section. For example, the while(1) loop in the main function is placed inside a user section as illustrated below: /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ /* USER CODE END 3 */ B.2 STM32CubeMX design choices for peripheral initialization STM32CubeMX generates peripheral _Init functions that can be easily identified thanks to the MX_ prefix: static void MX_GPIO_Init(void); static void MX_<Peripheral Instance Name>_Init(void); static void MX_I2S2_Init(void); An MX_<peripheral instance name>_Init function exists for each peripheral instance selected by the user (e.g, MX_I2S2_Init). It performs the initialization of the relevant handle structure (e.g, &hi2s2 for I2S second instance) that is required for HAL driver initialization (e.g., HAL_I2S_Init) and the actual call to this function: void MX_I2S2_Init(void) hi2s2.Instance = SPI2; hi2s2.Init.Mode = I2S_MODE_MASTER_TX; hi2s2.Init.Standard = I2S_STANDARD_PHILLIPS;

STM32CubeMX C code generation design choices and limitations UM1718 hi2s2.Init.DataFormat = I2S_DATAFORMAT_16B; hi2s2.Init.MCLKOutput = I2S_MCLKOUTPUT_DISABLE; hi2s2.Init.AudioFreq = I2S_AUDIOFREQ_192K; hi2s2.Init.CPOL = I2S_CPOL_LOW; hi2s2.Init.ClockSource = I2S_CLOCK_PLL; hi2s2.Init.FullDuplexMode = I2S_FULLDUPLEXMODE_ENABLE; HAL_I2S_Init(&hi2s2); By default, the peripheral initialization is done in main.c. If the peripheral is used by a middleware mode, the peripheral initialization can be done in the middleware corresponding .c file. Customized HAL_<IP Name>_MspInit() functions are created in the stm32f4xx_hal_msp.c file to configure the low level hardware (GPIO, CLOCK) for the selected IPs. B.3 STM32CubeMX design ch oices and limitations for middleware initialization B.3.1 Overview STM32CubeMX does not support C user code insertion in Middleware stack native files although stacks such as LwIP might require it in some use cases. STM32CubeMX generates middleware Init functions that can be easily identified thanks to the MX_ prefix: MX_LWIP_Init(); // defined in lwip.h file MX_USB_HOST_Init(); // defined in usb_host.h file MX_FATFS_Init(); // defined in fatfs.h file Note however the following exceptions:

  • No Init function is generated for FreeRTOS unless the user chooses, from the Project settings window, to generate Init functions as pairs of .c/.h files. Instead, a StartDefaultTask function is defined in the main.c file and CMSIS-RTOS native function (osKernelStart) is called in the main function.
  • If FreeRTOS is enabled, the Init functions for the other middlewares in use are called from the StartDefaultTask function in the main.c file. Example: void StartDefaultTask(void const * argument) /* init code for FATFS */ MX_FATFS_Init(); /* init code for LWIP */ MX_LWIP_Init(); /* init code for USB_HOST */ MX_USB_HOST_Init(); /* USER CODE BEGIN 5 */ /* Infinite loop */

UM1718 STM32CubeMX C code genera tion design choices and limitations 230 for(;;) osDelay(1); /* USER CODE END 5 */ B.3.2 USB Host USB peripheral initialization is performed within the middleware initialization C code in the usbh_conf.c file, while USB stack initialization is done within the usb_host.c file. When using the USB Host middleware, the user is responsible for implementing the USBH_UserProcess callback function in the generated usb_host.c file. From STM32CubeMX user interface, the user can select to register one class or all classes if the application requires switching dynamically between classes. B.3.3 USB Device USB peripheral initialization is performed within the middleware initialization C code in the usbd_conf.c file, while USB stack initialization is done within the usb_device.c file. USB VID, PID and String standard descriptors are configured via STM32CubeMX user interface and available in the usbd_desc.c generated file. Other standard descriptors (configuration, interface) are hard-coded in the same file preventing support for USB composite devices. When using the USB Device middleware, the user is responsible for implementing the functions in the usbd_<classname>_if.c class interface file for all device classes (e.g., usbd_storage_if.c). USB MTP and CCID classes are not supported. B.3.4 FatFs FatFs configuration is available in the ffconf.h generated file. The initialization of the SDIO peripheral for the FatFs SD Card mode and of the FMC peripheral for the FatFs External SDRAM and External SRAM modes are kept in the main.c file. Some files need to be modified by the user to match user board specificities (BSP drivers in STM32Cube embedded software package can be used as example):

  • bsp_driver_sd.c/.h generated files when using FatFs SD Card mode
  • bsp_driver_sram.c/.h generated files when using FatFs External SRAM mode
  • bsp_driver_sdram.c/.h generated files when using FatFs External SDRAM mode. Multi-drive FatFs is supported, which means that multiple logical drives can be used by the application (External SDRAM, External SRAM, SD Card, USB Disk, User defined). However support for multiple instances of a given logical drive is not available (e.g. FatFs using two instances of USB hosts or several RAM disks).

the interface between the middleware and the selected peripheral. FreeRTOS configuration is available in FreeRTOSConfig.h generated file. will be initialized within the same FreeRTOS thread in the main.c file. shall implement. This is highlighted by the tooltip (see Figure 199). Figure 199. FreeRTOS HOOK functions to be completed by user

done within the middleware initialization C code. shall be backed up since they will be lost at next STM32CubeMX generation. Starting with release 1.5, STM32CubeMX LwIP supports IPv6 (see Figure 202). DHCP must be disabled, to configure a static IP address. Figure 200. LwIP 1.4.1 configuration

Figure 201. LwIP 1.5 configuration

  • MEM_USE_POOLS: user C code to be added either in lwipopts.h or in cc.h (stack file).
  • PPP_SUPPORT, PPPOE_SUPPORT: user C code required
  • MEMP_SEPARATE_POOLS with MEMP_OVERFLOW_CHECK > 0: a stack patch required
  • MEM_LIBC_MALLOC & RTOS enabled: stack patch required
  • LWIP_EVENT_API: stack patch required In STM32CubeMX, the user must enable FreeRTOS in order to use LwIP with the netconn and sockets APIs. These APIs require the use of threads and consequently of an operating system. Without FreeRTOS, only the LwIP event-driven raw API can be used.

UM1718 STM32 microcontrollers naming conventions 230 Appendix C STM32 microcontrollers naming conventions STM32 microcontroller part numbers are codified following the below naming conventions:

  • Device subfamilies The higher the number, the more features available. For example STM32L0 line includes STM32L051, L052, L053, L061, L062, L063 subfamilies where STM32L06x part numbers come with AES while STM32L05x do not. The last digit indicates the level of features. In the above example: – 1 =Access line – 2 = with USB – 3 = with USB and LCD.
  • Pin counts – F = 20 pins – G = 28 pins – K = 32 pins – T = 36 pins – S = 44 pins – C = 48 pins – R = 64 pins (or 66 pins) – M = 80 pins – O = 90 pins – V = 100 pins – Q= 132 pins (e. g. STM32L162QDH6) –Z = 1 4 4 – I=176 (+25) – B = 208 pins (e. g.: STM32F429BIT6) – N = 216 pins
  • Flash memory sizes – 4 = 16 Kbytes of Flash memory – 6 = 32 Kbytes of Flash memory – 8 = 64 Kbytes of Flash memory – B = 128 Kbytes of Flash memory – C = 256 Kbytes of Flash memory – D = 384 Kbytes of Flash memory – E = 512 Kbytes of Flash memory – F = 768 Kbytes of Flash memory – G = 1024 Kbytes of Flash memory – I = 2048 Kbytes of Flash memory
  • Packages – B = SDIP –H = B G A

UM1718 STM32 microcontrollers power consumption parameters 230 Appendix D STM32 microcontrollers power consumption parameters This section provides an overview on how to use STM32CubeMX Power Consumption Calculator (PCC). Microcontroller power consumption depends on chip size, supply voltage, clock frequency and operating mode. Embedded applications can optimize STM32 MCU power consumption by reducing the clock frequency when fast processing is not required and choosing the optimal operating mode and voltage range to run from. A description of STM32 power modes and voltage range is provided below. D.1 Power modes STM32 MCUs support different power modes (refer to STM32 MCU datasheets for full details). D.1.1 STM32L1 series STM32L1 microcontrollers feature up to 6 power modes, including 5 low-power modes:

  • Run mode This mode offers the highest performance using HSE/HSI clock sources. The CPU runs up to 32 MHz and the voltage regulator is enabled.
  • Sleep mode This mode uses HSE or HSI as system clock sources. The voltage regulator is enabled and the CPU is stopped. All peripherals continue to operate and can wake up the CPU when an interrupt/event occurs.
  • Low- power run mode This mode uses the multispeed internal (MSI) RC oscillator set to the minimum clock frequency (131 kHz) and the internal regulator in low-power mode. The clock frequency and the number of enabled peripherals are limited.
  • Low-power sleep mode This mode is achieved by entering Sleep mode. The internal voltage regulator is in low- power mode. The clock frequency and the number of enabled peripherals are limited. A typical example would be a timer running at 32 kHz. When the wakeup is triggered by an event or an interrupt, the system returns to the Run mode with the regulator ON.
  • Stop mode This mode achieves the lowest power consumption while retaining RAM and register contents. Clocks are stopped. The real-time clock (RTC) an be backed up by using LSE/LSI at 32 kHz/37 kHz. The number of enabled peripherals is limited. The voltage regulator is in low-power mode. The device can be woken up from Stop mode by any of the EXTI lines.
  • Standby mode This mode achieves the lowest power consumption. The internal voltage regulator is switched off so that the entire V CORE domain is powered off. Clocks are stopped and the real-time clock (RTC) can be preserved up by using LSE/LSI at 32 kHz/37 kHz.

STM32 microcontrollers power consumption parameters UM1718 RAM and register contents are lost except for the registers in the Standby circuitry. The number of enabled peripherals is even more limited than in Stop mode. The device exits Standby mode upon reset, rising edge on one of the three WKUP pins, or if an RTC event occurs (if the RTC is ON). Note: When exiting Stop or Standby modes to enter the Run mode, STM32L1 MCUs go through a state where the MSI oscillator is used as clock source. This transition can have a significant impact on the global power consumption. For this reason, STM32CubeMX PCC introduces two transition steps: WU_FROM_STOP and WU_FROM_STANDBY. During these steps, the clock is automatically configured to MSI. D.1.2 STM32F4 series STM32F4 microcontrollers feature a total of 5 power modes, including 4 low-power modes:

  • Run mode This is the default mode at power-on or after a system reset. It offers the highest performance using HSE/HSI clock sources. The CPU can run at the maximum frequency depending on the selected power scale.
  • Sleep mode Only the CPU is stopped. All peripherals continue to operate and can wake up the CPU when an interrupt/even occurs. The clock source is the clock that was set before entering Sleep mode.
  • Stop mode This mode achieves a very low power consumption using the RC oscillator as clock source. All clocks in the 1.2 V domain are stopped as well as CPU and peripherals. PLL, HSI RC and HSE crystal oscillators are disabled. The content of registers and internal SRAM are kept. The voltage regulator can be put either in normal Main regulator mode (MR) or in Low- power regulator mode (LPR). Selecting the regulator in low-power regulator mode increases the wakeup time. The Flash memory can be put either in Stop mode to achieve a fast wakeup time or in Deep power-down to obtain a lower consumption with a slow wakeup time. The Stop mode features two sub-modes: – Stop in Normal mode (default mode) In this mode, the 1.2 V domain is preserved in nominal leakage mode and the minimum V12 voltage is 1.08 V. – Stop in Under-drive mode In this mode, the 1.2 V domain is preserved in reduced leakage mode and V12 voltage is less than 1.08 V. The regulator (in Main or Low-power mode) is in under-drive or low-voltage mode. The Flash memory must be in Deep-power- down mode. The wakeup time is about 100 µs higher than in normal mode.
  • Standby mode This mode achieves very low power consumption with the RC oscillator as a clock source. The internal voltage regulator is switched off so that the entire 1.2 V domain is powered off: CPU and peripherals are stopped. The PLL, the HSI RC and the HSE crystal oscillators are disabled. SRAM and register contents are lost except for registers in the backup domain and the 4-byte backup SRAM when selected. Only RTC and LSE oscillator blocks are powered. The device exits Standby mode when an

UM1718 STM32 microcontrollers power consumption parameters 230 external reset (NRST pin), an IWDG reset, a rising edge on the WKUP pin, or an RTC alarm/ wakeup/ tamper/time stamp event occurs.

  • VBAT operation It allows to significantly reduced power consumption compared to the Standby mode. This mode is available when the VBAT pin powering the Backup domain is connected to an optional standby voltage supplied by a battery or by another source. The VBAT domain is preserved (RTC registers, RTC backup register and backup SRAM) and RTC and LSE oscillator blocks powered. The main difference compared to the Standby mode is external interrupts and RTC alarm/events do not exit the device from VBAT operation. Increasing VDD to reach the minimum threshold does. D.1.3 STM32L0 series STM32L0 microcontrollers feature up to 8 power modes, including 7 low-power modes to achieve the best compromise between low-power consumption, short startup time and available wakeup sources:
  • Run mode This mode offers the highest performance using HSE/HSI clock sources. The CPU can run up to 32 MHz and the voltage regulator is enabled.
  • Sleep mode This mode uses HSE or HSI as system clock sources. The voltage regulator is enabled and only the CPU is stopped. All peripherals continue to operate and can wake up the CPU when an interrupt/event occurs.
  • Low-power run mode This mode uses the internal regulator in low-power mode and the multispeed internal (MSI) RC oscillator set to the minimum clock frequency (131 kHz). In Low-power run mode, the clock frequency and the number of enabled peripherals are both limited.
  • Low-power sleep mode This mode is achieved by entering Sleep mode with the internal voltage regulator in low-power mode. Both the clock frequency and the number of enabled peripherals are limited. Event or interrupt can revert the system to Run mode with regulator on.
  • Stop mode with RTC The Stop mode achieves the lowest power consumption with, while retaining the RAM, register contents and real time clock. The voltage regulator is in low-power mode. LSE or LSI is still running. All clocks in the V CORE domain are stopped, the PLL, MSI RC, HSE crystal and HSI RC oscillators are disabled. Some peripherals featuring wakeup capability can enable the HSI RC during Stop mode to detect their wakeup condition. The device can be woken up from Stop mode by any of the EXTI line, in 3.5 µs, and the processor can serve the interrupt or resume the code.
  • Stop mode without RTC This mode is identical to “Stop mode with RTC “, except for the RTC clock which is stopped here.
  • Standby mode with RTC The Standby mode achieves the lowest power consumption with the real time clock running. The internal voltage regulator is switched off so that the entire V CORE domain

STM32 microcontrollers power consumption parameters UM1718 is powered off. The PLL, MSI RC, HSE crystal and HSI RC oscillators are also switched off. The LSE or LSI is still running. After entering Standby mode, the RAM and register contents are lost except for registers in the Standby circuitry (wakeup logic, IWDG, RTC, LSI, LSE Crystal 32 KHz oscillator, RCC_CSR register). The device exits Standby mode in 60 µs when an external reset (NRST pin), an IWDG reset, a rising edge on one of the three WKUP pins, RTC alarm (Alarm A or Alarm B), RTC tamper event, RTC timestamp event or RTC Wakeup event occurs.

  • Standby mode without RTC This mode is identical to Standby mode with RTC, except that the RTC, LSE and LSI clocks are stopped. The device exits Standby mode in 60 µs when an external reset (NRST pin) or a rising edge on one of the three WKUP pin occurs. Note: The RTC, the IWDG, and the corresponding clock sources are not stopped automatically by entering Stop or Standby mode. The LCD is not stopped automatically by entering Stop mode. D.2 Power consumption ranges STM32 MCUs power consumption can be further optimized thanks to the dynamic voltage scaling feature: the main internal regulator output voltage V12 that supplies the logic (CPU, digital peripherals, SRAM and Flash memory) can be adjusted by software by selecting a power range (STM32L1 and STM32L0) or power scale (STM32 F4). Power consumption range definitions are provided below (refer to STM32 MCU datasheets for full details). D.2.1 STM32L1 series feature 3 V CORE ranges
  • High Performance Range 1 (VDD range limited to 2.0-3.6 V), with the CPU running at up to 32 MHz The voltage regulator outputs a 1.8 V voltage (typical) as long as the VDD input voltage is above 2.0 V. Flash program and erase operations can be performed.
  • Medium Performance Range 2 (full VDD range), with a maximum CPU frequency of

16 MHz

At 1.5 V, the Flash memory is still functional but with medium read access time. Flash program and erase operations are still possible.

  • Low Performance Range 3 (full VDD range), with a maximum CPU frequency limited to

4 MHz (generated only with the multispeed internal RC oscillator clock source)

At 1.2 V, the Flash memory is still functional but with slow read access time. Flash Program and erase operations are no longer available.

UM1718 STM32 microcontrollers power consumption parameters 230 D.2.2 STM32F4 series feature several VCORE scales The scale can be modified only when the PLL is OFF and when HSI or HSE is selected as system clock source.

  • Scale 1 (V12 voltage range limited to 1.26-1.40 V), default mode at reset HCLK frequency range = 144 MHz to 168 MHz (180 MHz with over-drive). This is the default mode at reset.
  • Scale 2 (V12 voltage range limited to 1.20 to 1.32 V) HCLK frequency range is up to 144 MHz (168 MHz with over-drive)
  • Scale 3 (V12 voltage range limited to 1.08 to 1.20 V), default mode when exiting Stop mode HCLK frequency ≤120 MHz. The voltage scaling is adjusted to fHCLK frequency as follows:
  • STM32F429x/39x MCUs: – Scale 1: up to 168 MHz (up to 180 MHz with over-drive) – Scale 2: from 120 to 144 MHz (up to 168 MHz with over-drive) – Scale 3: up to 120 MHz.
  • STM32F401x MCUs: No Scale 1 – Scale 2: from 60 to 84 MHz – Scale 3: up to 60 MHz.
  • STM32F40x/41x MCUs: – Scale 1: up to 168 MHz – Scale 2: up to 144 MHz D.2.3 STM32L0 series feature 3 V CORE ranges
  • Range 1 (VDD range limited to 1.71 to 3.6 V), with CPU running at a frequency up to

32 MHz

  • Range 2 (full VDD range), with a maximum CPU frequency of 16 MHz
  • Range 3 (full VDD range), with a maximum CPU frequency limited to 4.2 MHz.

compatible with STM32CubeMX generated C code. Figure 203. STM32Cube Embedded Software package STM32CubeL0 and STM32CubeL1 embedded software packages are available on st.com. provided in the package to get started with STM32 application development.

Table 16. Document revision history 17-Feb-2014 1 Initial release. MCU initialization parameters. installing ‘Java 7 update 45’ or a more recent version of the JRE?. Updated Section 6.1: Creating a new STM32CubeMX Project.

Added Figure 22: New Project window - board selector. Updated Figure 40: Project Settings Code Generator. Modified step 3 in Section 4.8: Project Settings window. Updated introduction of Section 4.13: Clock tree configuration view. Section 4.14.4: Power sequence step parameters glossary. Updated Section 5: STM32CubeMX C Code generation overview. Section 6.2: Configuring the MCU pinout. Generating GPIO initialization C code (STM32F1 series only). Updated Section 4.14.2: Configuring a step in the power sequence. Table 16. Document revision history (continued)

tree configuration now available on all STM32 series. Updated Eclipse IDEs in Section 3.1.3: Software requirements. Updated Figure 44: About window. Updated Table 9: STM32CubeMX Chip view - Icons and color scheme. Updated Section 4.12.1: IP and Middleware Configuration window. Updated Section 4.13.1: Clock tree configuration functions. consumption sequence, Figure 88: PCC Edit Step window. Added Section 5.2: Custom code generation. 3 configuration window in Section 6.6.2: Configuring the peripherals . Updated Figure 137: GPIO mode configuration. and A.3: One block = one peripheral mode. Updated Appendix A.8: Mapping a function individually . Updated Appendix B.3.1: Overview. Updated Appendix D.1.3: STM32L0 series.

Upgraded STM32CubeMX released number to 4.14.0. from templates in Section 2.2: Key features. and Section 3.4.3: Running STM32CubeMX plug-in from Eclipse IDE. Pinout menus (Pinout tab not selected) in Section 4.4.3: Pinout menu. Modified Table 6: Window menu. Updated Section 4.5: Output windows. configuration grouped by IP and Figure 73: Multiple Pins Configuration. Updated Section 4.12.5: NVIC Configuration window. Section 4.6: Import Project window ). config comands as well as set dest_path <path> example. Updated Generate Code menu description in Table 4: Project menu. Updated Set unused GPIOs menu in Table 5: Pinout menu. interruptions using the NVIC tab view. Added Section 4.12.6: FreeRTOS middleware configuration view.