AN4989 STMICROELECTRONICS | Alldatasheet

Document overview

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

Technical content

Datasheet sections

  • 1 Foreword
  • 1.1 Software versions
  • 1.2 Acronyms
  • 2 STM32 ecosystem outlines
  • 2.1 Hardware development tools
  • 2.1.1 Hardware kits
  • 2.1.2 ST-LINK probe
  • 2.1.3 Alternative debugger probes
  • 2.2 Software development tools
  • 2.2.1 STM32CubeMX
  • 2.2.2 Partner IDEs
  • 2.2.3 STMStudio
  • 2.2.4 ST-LINK utility
  • 2.3 Embedded software
  • 2.4 Information and sharing
  • 2.4.1 Documentation
  • 2.4.2 ST Community
  • 2.4.3 STM32 Education
  • 3 Compiling for debug
  • 3.1 Optimization
  • 3.1.1 IAR™ EWARM
  • 3.1.2 Keil ® MDK-ARM µVision
  • 3.1.3 SW4STM32
  • 3.2 Debugging information
  • 3.2.1 IAR™ EWARM
  • 3.2.2 Keil
  • 3.2.3 SW4STM32
  • 4 Connecting to the board
  • 4.1 SWD/JTAG pinout
  • 4.2 Reset and connection mode

Datasheet sections

  • 8.2.1 Configuration with STM32CubeMX
  • 8.2.2 HAL_RCC_MCOConfig
  • 8.2.3 STM32 Series differences
  • 9 From debug to release
  • 10 Troubleshooting

obvious, particularly for inexperienced users. This application note applies to the microcontrollers listed in Table 1. Table 1. Applicable products

4.2.3 Keil

1 Foreword

1.1 Software versions

The various examples in this application note are illustrated on basis of the following versions of the tools:

  • IAR™ EWARM: V8.10.1
  • Keil® MDK-ARM µVision: V5.22
  • SW4STM32: V2.0.0
  • ST-LINK utility: V4.0.0

1.2 Acronyms

  • AN: Application note
  • CMSIS: Cortex microcontroller software interface standard
  • HAL: Hardware abstraction layer (software library)
  • IDE: Integrated development environment
  • JTAG: Joint Test Action Group
  • MCO: Microcontroller clock output
  • MCU: Microcon troller unit
  • NVIC: Nested vector interrupt controller
  • PM: Programming manual
  • RM: Reference manual
  • SB: Solder bridge
  • SWD: Serial wire debug
  • SWO: Single wire output
  • SWV: Single wire viewer
  • VCP: Virtual-COM port

2 STM32 ecosystem outlines

develop a project with STM32. Figure 1. STM32 ecosystem overview

2.1 Hardware development tools

LINK probes and alternative debugger interfaces.

2.1.1 Hardware kits

  • Nucleo boards
  • Discovery kits
  • Evaluation boards (EVAL)

quickly create prototypes based on STM32 MCU. Figure 2. Nucleo-144, Nucleo-64 and Nucleo-32 boards large number of specialized application hardware add-ons. Nucleo-64 boards include Arduino™ Uno rev3 and ST morpho connectors. Nucleo-32 boards include Arduino™ Nano connectors. documentation sets are available at www.st.com.

software examples allow to fully benefit from the devices features and added values. Figure 3. Discovery board example With the integrated debugger/programmer the Discovery kits are ideal for prototyping. documentation sets are available at www.st.com.

development platform for the ARM® Cortex® STM32 MCUs. Figure 4. EVAL board example Section 2.1.2: ST-LINK probe. Alternative debugger probes on page 15. from default. Refer to the specific board user manual.

2.1.2 ST-LINK probe

STM32 microcontroller located on an application board.

  • Stand-alone in-circuit debugger
  • Embedded in all STM32 hardware kits (Nucleo boards, Discovery kits, EVAL boards) Figure 5 shows the first ST-LINK version on the left and the ST-LINK/V2 and ST-LINK/V2- ISOL stand-alone probes on the right.

Figure 5. ST-LINK, ST-LINK/V2, and ST-LINK/V2-ISOL stand-alone probes Figure 6 shows an example of an embedded ST-LINK/V2 as part of a Nucleo board. Figure 6. On-board ST-LINK/V2 on Nucleo

  • 5 V power supplied by a USB connector
  • USB 2.0 full-speed-compatible interface
  • USB standard A to Mini- B cable
  • JTAG/serial wire debug (SWD) specific features: – 1.65 V to 3.6 V application voltage supported on the JTAG/SWD interface and 5 V tolerant inputs – JTAG cable for connection to a standard JTAG 20-pin pitch 2.54 mm connector – JTAG supported – SWD and serial wire viewer (SWV) communication supported
  • Device Firmware Upgrade (DFU) feature supported
  • Status LED which blinks during communication with the PC
  • Operating temperature 0 °C to 50 °C
  • 1000 V rms high-isolation voltage (ST-LINK/V2-ISOL only) Embedded versions usually supports the following additional features:
  • Virtual-COM-port interface on USB. (VCP)
  • Mass storage interface on USB The availability of these additional features depends on software version. In order to identify the ST-LINK version on a board and the related features associated with it, please refer STMicroelectronics technical note Overview of the ST-LINK embedded in STM32 MCU Nucleo, Discovery Kits and Eval Boards (TN1235). On-board ST-LINK does not support JTAG port. Note: For Nucleo and Discovery, JTAG port signal can be wired through Morpho / Arduino™ connectors. On EVAL boards, there is a dedicated 20-pin connector. The use of ST-LINK requires the software packages listed in Table 2. Note: STSW-LINK007 is included in STSW-LINK004. STSW-LINK009 is included in most IDE installation packages (IAR™, Keil ®, SW4STM32) and tools. Tip: It is recommended to use the latest firmware version of the on-board ST-LINK interface. Firmware upgrade can be perf ormed thanks to the ST-LINK utility software (refer to Section 2.2.4: ST-LINK utility on page 19).

Table 2. ST-LINK software pack

2.1.3 Alternative debugger probes

providing features equivalent to the ones provided by ST-LINK.

  • U-Link Pro in combination with Keil® MDK-ARM µVISION
  • I-Jet™ Trace in combin ation with IAR™ EWARM For a complete catalog of solutions, refer to www.st.com.

2.2 Software development tools

complete range of software tools. allowing to configure and initialize the MCU or monitor its behavior in run time. It offers a complete flow, from configuration up to monitoring as illustrated in Figure 7. Figure 7. STM32 software development tools

STM32 ecosystem outlines AN4989

2.2.1 STM32CubeMX

STM32CubeMX is a graphical tool that allows to easily configure STM32 microcontrollers and to generate the corresponding initialization C code through a step-by-step process. 1. The first step consists in selecting the STM32 microcontroller that matches the required set of peripherals. MCU can be selected as stand-alone for custom PCB (MCU Selector) or pre-integrated into one of STMicroelectronics hardware kit (Board Selector) 2. In the second step, the user must conf igure each required embedded software thanks to a pinout-conflict solver, a clock-tree setting helper, a power-consumption calculator, and a utility performing MCU peripheral configuration (GPIO, USART, and others) and middleware stacks (USB, TCP/IP, and others). 3. Finally, the user launches the generation of the initialization C code based on the selected configuration. This code is ready to be used within several development environments. The user code is kept at the next code generation. Key features

  • Intuitive STM32 microcontroller selection
  • Microcontroller graphical configuration
  • Pinout with automatic conflict resolution
  • Clock tree with dynamic validation of configuration
  • Peripherals and middleware functional modes and initialization with dynamic validation of parameter constraints
  • Power consumption calculation for a user-defined application sequence
  • C code project generation covering STM32 microcontroller initialization compliant with IAR™, Keil ® and GCC compilers.
  • Available as a standalone software running on Windows®, Linux®, and macOS™ operating systems, or through Eclipse plug-in

AN4989 STM32 ecosystem outlines

2.2.2 Partner IDEs

In this application note, all topics are declined for the three main IDEs: 1. IAR™ EWARM 2. Keil ® MDK-ARM µVISION 3. SW4STM32 IAR™ EWARM The IAR Embedded Workbench® for ARM® (IAR™ EWARM) is a software development suite delivered with ready-made device configuration files, flash loaders and 4300 example projects included. IAR Systems ® and STMicroelectronics closely cooperate in supporting 32-bit ARM® Cortex®-M based microcontrollers. Key Features

  • Key components: – Integrated development environment with project management tools and editor – Highly optimizing C and C++ compiler for ARM – Automatic checking of MISRA C rules (MISRA C:2004) –A R M ® EABI and CMSIS compliance – Extensive HW target system support – Optional I-jet™ and JTAGjet™-Tra ce in-circuit debugging probes – Power debugging to visualize power cons umption in correlation with source code – Run-time libraries including source code – Relocating ARM ® assembler – Linker and librarian tools – C-SPY ® debugger with ARM® simulator, JTAG support and support for RTOS- aware bugging on hardware – RTOS plugins available from IAR™ Systems and RTOS vendors – Over 3100 sample projects for EVAL boards from many different manufacturers – User and reference guides in PDF format – Context-sensitive on-line help
  • Chip-specific support: – 4300 example projects included for STMicroelectronics EVAL boards – Support for 4 Gbyte applications in ARM ® and Thumb® mode – Each function can be compiled in ARM ® or Thumb® mode – VFP Vector Floating Point co-processor code generation
  • Intrinsic NEON™ support
  • ST-LINK and ST-LINK V2 support This product is supplied by a third party not affiliated to ST. For the latest information on the specification, refer to the IAR™ web site at http://www.iar.com. Keil® MDK-ARM µVision The MDK-ARM-STM32 is a complete software development environment for Cortex®-M microcontroller-based devices. It includes the µVision IDE/Debugger, ARM®C/C++ compiler

STM32 ecosystem outlines AN4989 and essential middleware components. The STM32 peripherals can be configured using STM32CubeMX and the resulting project exported to MDK-ARM. Free MDK-ARM licenses can be activated for both STM32F0 and STM32L0 Series using the following Product Serial Number (PSN): U1E21-CM9GY-L3G4L. This product is supplied by a third party not affiliated to ST. For the latest information on the specification refer to the third party's website: http://www2.keil.com/stmicroelectronics- stm32. Key Features

  • Complete support for Cortex®-M devices
  • ARM® C/C++ compilation toolchain
  • uVision IDE, debugger and simulation environment
  • CMSIS Cortex® Microcontroller Software Interface Standard compliant
  • ST-LINK support
  • Multi-language support: English, Chinese, Japanese, Korean SW4STM32 The System Workbench for STM32 toolchain, called SW4STM32, is a free multi-OS software development environment based on Eclipse, which supports the full range of STM32 microcontrollers and associated boards. The SW4STM32 toolchain may be obtained from the website www.openstm32.org, which includes forums, blogs, and trainings for technical support. Once registered to this site, users get installation instructions at the Documentation > System Workbench page to proceed with the download of the free toolchain. The SW4STM32 toolchain and its collaborative website have been built in collaboration with AC6, a service company providing training and consultancy on embedded systems. This product is supplied by a third party not affiliated to ST. For the latest information on the specification, refer to the third party's website: www.ac6.fr. Key Features
  • Comprehensive support for STM32 microcontrollers, STM32 Nucleo boards, Discovery kits and EVAL boards, as well as STM32 firmware (Standard Peripheral library or STM32Cube HAL)
  • GCC C/C++ compiler
  • GDB-based debugger
  • Eclipse IDE with team-work management
  • ST-LINK support
  • No code size limit
  • Multiple OS support: Windows ® (32 and 64 bits), Linux (64 bits) and MacOS™ In case of installation or update through the Eclipse Help -> Install New software... menu, the following dependences for SW4STM32 V2.0.0 are required:
  • Eclipse Mars2 or Neon
  • CDT 8.8.1
  • Java 1.8

AN4989 STM32 ecosystem outlines All above dependences are properly managed in case of All-in-one installer package or through Help -> Check For Updates (recommended).

2.2.3 STMStudio

STMicroelectronics STMStudio helps debug and diagnose STM32 applications at run time by reading and displaying their variables in real-time. Running on a PC, STM Studio interfaces with STM32 MCUs via the standard ST-LINK probe. STMStudio is a non-intrusive tool, preserving the real-time behavior of applications. STMStudio perfectly complements traditional debugging tools to fine tune applications. It is well suited for debugging applications which cannot be stopped, such as motor control applications. Different graphic views are available to match the needs of debugging and diagnosis or to demonstrate application behavior. Key Features

  • Runs on PCs with Microsoft® Windows® OS (XP, Vista, 7, 8, or 10)
  • Connects to any STM32 via ST-LINK (JTAG or SWD protocols)
  • Reads on-the-fly (non intrusive) variables from RAM while application is running
  • Parses DWARF debugging information in the ELF application executable file
  • Two types of viewer: – Variable viewer: real-time wave forms, oscilloscope-like graphs – TouchPoint viewer: association of two variables, one on the X axis, one on the Y axis
  • Possibility to log data into a file, and replay later (exhaustive record display, not real- time) More information about the way to use STMStudio are available in STMicroelectronics user manual Getting started with STMStudio (UM1025).

2.2.4 ST-LINK utility

STM32 ST-LINK utility (STSW-LINK004) is a full-featured software interface for programming STM32 microcontrollers. It provides an easy-to-use and efficient environment for reading, writing and verifying a memory device. The tool offers a wide range of features to program STM32 internal memories (Flash, RAM, OTP and others), external memories, to verify the programming content (checksum, verify during and after programming, compare with file) and to automate STM32 programming. STM32 ST-LINK utility is delivered with a graphical user interface (GUI) and with a command line interface (CLI).

STM32 ecosystem outlines AN4989 Key Features

  • Free software
  • Supports Motorola S19, Intel HEX and binary formats
  • Load, Edit and Save executable and data files generated by the Assembler/Linker or C compilers
  • Erase, Program, View and Verify device Flash memory contents
  • Program, Erase and Verify external memories with examples of external flash loaders, for users to develop loaders for specific external memories
  • Automate STM32 programming (Erase, Verify, Programming, Configuring option bytes, calculate checksum)
  • Programming One Time Programmable memory
  • Supports Programming and Configuring Option bytes
  • Offers a command line interface
  • Compare file with target memory
  • Supports memory and core status view in Live-update mode
  • ST-LINK/V2 firmware upgrade In debug context ST-LINK is useful:
  • To check and update ST-LINK/V2 firmware in case of connection issue
  • Recover connection to a board in case of stuck in permanent Low-power or secure state.
  • Usage of SWV for printf debugging (Refer to Chapter 7: Printf debugging on page 58) Refer to STMicroelectronics user manual STM32 ST-LINK utility software description (UM0892).

2.3 Embedded software

The STM32Cube embedded software libraries provides:

  • The HAL hardware abstraction layer, enabling portability between different STM32 devices via standardized API calls
  • The Low-Layer (LL) APIs, a light-weight, optimized, expert oriented set of APIs designed for both performance and runtime efficiency
  • A collection of Middleware components, like RTOS, USB library, file system, TCP/IP stack, Touch sensing library or Graphic Library (depending on the MCU series)
  • A complete set of code examples running on STMicroelectronics boards: STM32 Nucleo, Discovery kits and EVAL boards Tip: There is a fair chance that a Cube Pr oject example matches the project in design. At project start or if an issue is met, it is worth browsing the complete project list package content available in CubeLibraryFolder\\Projects\\ STM32CubeProjectsList.html (refer to Figure 8).

Figure 8. STM32CubeProjectList screenshot

2.4 Information and sharing

Figure 9. Get connected to STM32 world

2.4.1 Documentation

of the main technical documents with a short description of their contents. Table 3. STMicroelectronics documentation guide ES Errata Sheet Contained known issues and device limitation.

STM32 ecosystem outlines AN4989 Tip: The MCU Finder application can be useful for document access and bookmarking in addition to its primary usage for identifying the suitable STM32 product. The MCU Finder application is available for use on PC, smartphone, and tablet. More information is available on www.st.com. Trick: When an Internet search engine is used to get access to STMicroelectronics documents, it is advised to search with an explicit mention of STMicroelectonics web site so that references to genuine documents are obtained. In the Google Toolbar™ search bar, the following syntax can be used: “[Document reference or key word]” site:www.st.com filetype:pdf

2.4.2 ST Community

STMicroelectronics new community is now live and ready for receiving questions, sharing projects and collaborating among fellow community members. The focus is on collaboration because the primary purpose of this community is to share with peers and help them in a transparent way that showcases the world of STMicroelectronics products, activities and achievements. The home page of ST Community is https://community.st.com/welcome. For any problem met, it is interesting to first browse the STM32 Forum for related topics and eventually to post a new one if no relevant thread is found.

2.4.3 STM32 Education

STM32 education material is available on-line at www.st.com (search for STM32 Education). This site provides free educational resources created by STMicroelectronics engineers for bringing an STM32 project to life. On this site, a user learns at his own pace, watches classes as per his own schedule, anytime, anywhere, on any device, or apply to one of the live learning sessions led by STMicroelectronics experts at a nearby location. Content:

  • Online Training
  • MOOC
  • Videos
  • Webinar
  • Textbooks
  • ST training courses
  • Partner training courses

3 Compiling for debug

This chapter reviews the various options for debug-friendly compiling solutions.

3.1 Optimization

most cases, this reduces or even prevents program debugging.

  • Problem to set or reach a breakpoint. Some lines are not accessible.
  • Impossibility to evaluate a variable (watch feature).
  • Inconsistency while stepping (what I get, is not what I see). Therefore, for efficient debugging it is recommended to modify the code optimization option.

3.1.1 IAR™ EWARM

Figure 10. IAR™ EWARM Optimization option

3.1.2 Keil ® MDK-ARM µVision

Figure 11. Keil® µVision Code Optimization option Keil® documentation suggests that Level1 (-O1) can be a suitable alternative for debug.

3.1.3 SW4STM32

Figure 12. SW4STM32 Optimization Level setting of optimization while maintaining fast compilation and a good debugging experience.

3.2 Debugging information

Debugging information is mandatory to set breakpoint or get the content of a variable.

3.2.1 IAR™ EWARM

Figure 13. IAR™ Generate debug Information option

3.2.2 Keil ®-MDK-ARM µVision

Debug Information Tick box is accessible in Options -> Output Pane. Figure 14. Keil® Debug Information option

3.2.3 SW4STM32

Figure 15. SW4STM32 Debug information option

  • None (-g0): Level 0 produces no debug information at all; -g0 negates -g.
  • Minimal (-g1): Level 1 produces minimal information, enough for making backtraces in parts of the program for which no debug is planned. This includes descriptions of functions and external variables, and line number tables, but no information about local variables.
  • Default (-g/-g2): Produce debugging information in the operating system's native format (stabs, COFF, XCOFF, or DWARF). GDB can work with this debugging information.
  • Maximal (-g3): Level 3 includes extra information, such as all the macro definitions present in the program. Some debuggers support macro expansion when -g3 is used. The same pane contains the options to add profiling information. For further information, refer to Section 3.1 Option Summary available at http://gcc.gnu.org.

4 Connecting to the board

knowledge about this topic can save time in identifying and fixing the issue. fix issues related to connection.

4.1 SWD/JTAG pinout

Nothing specific is required in the application code to make SWD work. are not switched to some alternate functions or affected by I/O settings modifications. board. (Refer to Section 4.2).

  • Reset, shown by the pins colored in gray in Figure 16
  • Reserved but inactive shown by the pins colored in orange in Figure 17
  • Active shown by the pins colored in green in Figure 18

Figure 16. SWD pins PA13 and PA14 in Reset state under STM32CubeMX

AN4989 Connecting to the board Especially since JTAG is using more pins, users should be aware that it is at the expense of using some IPs. Refer to the product datasheet for a detailed presentation of the default and alternative function mapping for each pin.

4.2 Reset and connection mode

This section reviews the reset and connection mode available while using ST-LINK/V2 debug interface.

4.2.1 Presentation

Connection mode and reset mode are 2 different but dependent concepts: Reset mode can be either:

  • Hardware: drive the NRST pin of the MCU. In all STMicroelectronics hardware kits, the debugger can drive this NRST through ST-LINK/V2. Hint: On Nucleo, check that releva nt Solder Bridge SB12 is not OFF.
  • Software (write to core register) – System: Core and all Peripheral SOC IPs are reset – Core: Only ARM ® Cortex® is reset Connection mode can be either:
  • Normal: Debugger takes control through JTAG/SWD port and starts execution after a software reset. This is working only if JTAG/SWD is available: – GPIO correctly configured and clocked – FCLK or HCLK enabled – Main Power domain or Low-Power debug active
  • ConnectUnderReset: Debugger takes control while asserted NRST pin, setting GPIO and clock into there default state. This is required in case of a reconnection to a system in Low-Power mode or which has changed SWD pin to alternate functions.
  • Hotplug: Debugger connect without reset nor halt. Once connected, the user can chose to perform the required action (typically halt to get where the program stands and read registers or memory for instance). Reset and Connection mode are differently accessible and exposed depending on tool and IDE.

4.2.2 IAR™ EWARM

Reset and Connection mode are seen as a single reset mode option as shown in Figure 19. Figure 19. Reset Mode in IAR8.10: screenshot

  • System (default):Normal Connection. Software System Reset prior to jump at main.
  • Core:Normal Connection. Software Core Reset prior to jump at main.
  • Software:Normal Connection. No Reset prior to jump and stop at main.
  • Hardware: Normal Connection. Assert NRST MCU pin prior to jump to main.
  • Connect during reset: Connection while asserted Hardware NRST. Hotplug connection is accessible with "Attach to running Target" function in project menu.

4.2.3 Keil ® MDK-ARM µVISION

Figure 20. Connect and Reset option Keil®

  • Normal just stops the CPU at the currently executed instruction after connecting.
  • with Pre-reset applies a hardware reset (HW RESET) before connecting to the device.
  • under Reset holds the hardware reset (HW RESET) signal active while connecting to the device. Use this option when the user program disables the JTAG/SW interface by mistake. Reset after Connect: performs (if enabled) a reset operation as defined in the Reset drop- down list (see below) after connecting to the target. When disabled, the debugger just stops the CPU at the currently executed instruction after connecting the target.

vary with the selected device.

  • Autodetect selects the best suitable reset method for the target device. This can be a specialized reset or standard method. If Autodetect finds an unknown device, it uses the SYSRESETREQ method.
  • HW RESET performs a hardware reset by asserting the hardware reset (HW RESET) signal.
  • SYSRESETREQ performs a software reset by setting the SYSRESETREQ bit. The Cortex®-M core and on-chip peripherals are reset.
  • VECTRESET performs a software reset by setting the VECTRESET bit. Only the Cortex®-M core is reset. On-chip peripherals are not reset. For some Cortex®-M devices, VECTRESET is the only way they may be reset. However, VECTRESET is not supported on Cortex®-M0, Cortex®-M0+, Cortex®-M1, and ARM®v8-M cores. Refer to http://www.keil.com/ Hotplug If all of the following options are disabled, no hardware reset is performed at debugger start:
  • Options For Target - Debug - Load Application at startup
  • Options For Target - Debug - Settings - Reset after connect (with Options For Target - Debug - Settings - Connect selected as NORMAL)
  • Options For Target - Utilities - Update Target before Debugging

Figure 21. Keil® hotplug step1

Figure 22. Keil® hotplug step2

Figure 23. Keil® hotplug step3 LOAD can be automated using an Initialization File under Options For Target - Debug. To go further, refer to http://www.keil.com/.

4.2.4 SW4STM32

Show generator options as presented in Figure 24 and Figure 25. Figure 24. Access to Generator Options in SW4STM32 V2.0.0

Figure 25. Select Generator Options Reset Mode in SW4STM32 V2.0.0 The Mode Setup group allows to set up the Reset Mode along with other debug behaviors.

  • Reset Mode as Connect under reset: asserts hardware reset and then connects to the target (under reset).
  • Reset Mode as Hardware reset: performs a hardware reset and then connects to the target.
  • Reset Mode as Software system reset: does not perform any hardware reset but connects to the target and performs a software system reset. In case of problem to connect to the board with SW4STM32, make sure that NRST from ST-LINK is properly connected to STM32 NRST. Hotplug mode is not proposed by SW4STM32. ST-LINK utility can be used instead.

4.2.5 ST-LINK utility

description in Section 4.2.1 on page 31. Figure 26. Connection and reset mode in ST-Link utility check the NRST connection on the board.

Connecting to the board AN4989

4.3 Low-power case

By default, the debug connection is lost if the application puts the MCU in Sleep, Stop, or Standby mode while the debug features are used. This is due to the fact that the Cortex®-M core is not clocked in any of these modes. However, the setting of dedicated configuration bits in the DBGMCU_CR register allows software debug even when the low-power modes are used extensively. Refer to the PWR and DBG sections of the reference manual for details. Appendix A: Managing DBGMCU registers on page 78 guides the user through the various means to manage DBGMCU depending on IDE and needs. Caution: In order to reduce power consumption, some applications turn all GPIOs to analog input mode, including SWD GPIOs. This is the case for all PWR examples provided in STM32Cube (debug connection is lost after SystemPower_Config() which sets all GPIOs in Analog Input State). Enabling low-power debug degrades power consumption performance by keeping some clocks enabled and by preventing to optimize GPIO state. Even if this is useful for functional debugging, it has anyhow to be banned as soon as the target is to measure/enhance power consumption. All DBGMCU registers values are kept while reset. Users must pay attention not to let debug or unwanted states when returning to normal execution (refer to Section 9: From debug to release on page 76).

AN4989 Breaking and stepping into code

5 Breaking and stepping into code

This chapter provides users with highlights about a few points affecting system behavior at code break.

5.1 Debug support for timers, RTC, watchdog, BxCAN and I2C

During a breakpoint, it is necessary to choose how the counter of timers, RTC and watchdog should behave:

  • They can continue to count inside a breakpoint. This is usually required when a PWM is controlling a motor, for example.
  • They can stop counting inside a breakpoint. This is required for watchdog purposes. For the BxCAN, the user can choose to block the update of the receive register during a breakpoint. For the I2C, the user can choose to block the SMBUS timeout during a breakpoint. Those options are accessible in DBGMCU freeze registers (DBGMCU_APB1FZR1, DBGMCU_APB1FZR2) which can be written by the debugger under system reset. If the debugger host does not support these features, it is still possible to write these registers by software. Refer to Appendix A: Managing DBGMCU registers on page 78 to find suitable ways to handle debug options depending on IDEs and needs.

5.2 Debug performance

To save flashing time and improve debugger reactivity when stepping, make sure that the higher SWD frequency possible is used with the probe. When using ST-LINK utility, IAR™ EWARM, or Keil ® MDK-ARM µVISION speed is set at 1.8 MHz by default. On system with a core clock greater than 1 MHz, it is safe to use the highest 4 MHz SWD speed.

5.2.1 IAR™ EWARM

Figure 27. IAR™ EWARM ST -LINK SWD Speed setting

5.2.2 Keil ® MDK-ARM µVISION

Figure 28. Keil® SWD Speed Setting

5.2.3 SW4STM32

clicking on the Show generator options as presented in Figure 29. Figure 29. Access to Generator Options in SW4STM32 V2.0.0

Figure 30. Generator Options Connection Setup in SW4STM32 V2.0.0 overview of debug capabilities for each Cortex®-M type.

Breaking and stepping into code AN4989

5.3 Secure platform limitation

The STMicroelectronics platform provides the following code protection means. RDP: ReadOut Protection Prevents Flash Memory access through the JTAG for ALL Flash memory. PcROP: Proprietary Code ReadOut Protection Prevents read access of configurable Flash memory areas performed by the CPU execution of malicious third-party code (Trojan Horse). WRP: Prevents accidental or malicious write/erase operations. For further details please refer to the reference manual or section Training L4 on STMicroelectronics website www.st.com. The next sections provide additional details on the expected behavior of the secure applications.

5.3.1 RDP

  • Level 0: No Protection. This is the factory default mode allowing all accesses.
  • Level 1: Read Protection. Any access to Flash or protection extension region generates a system hard-fault which blocks all code execution until the next power-on reset. A simple reset does re- enable code execution; power must be switched off and on so that power-on reset enables code execution. The restriction depends on the STM32 Series as described in Table 4.

Thus, any attempt to load, or connect to, an application running from Flash crashes. It is still possible to load, execute and debug an application in SRAM. Going back to RDP Level 0 completely erases the Flash.

  • Level 2: No Debug. JTAG/SWD connexion is killed. There is no way back. In this case, nobody - even STMicroelectronics - can perform any analysis of defective parts.

5.3.2 PCROP

can locate a proprietary code. This prevents malicious software or debugger from reading sensitive code.

  • Step-into PCROP function is tolerated but ignored (Step-over)
  • Access to protected memory through debugger trigs Flash Interruption (Instrument NMIHandler) and return default pattern for the whole area For further details refer to section Memory Protection in the reference manual of the device.

Table 4. STM32 Series RDP protection extension

6 Exception handling

It is usually helpful, or even mandatory in complex project, to properly trap and find root cause of software exception like HardFault and NMI. This chapter intends to make the user aware of a few techniques used to help investigating such issue. In order to get deeper into the subject, the user can usefully refer to Joseh Yiu’s work and book collection The Definitive Guide to ARM-Cortex-M, and to Carmelo Noviello’s recent on- line guide Mastering STM32.

6.1 Default weak Handlers

By default Handlers are implemented as __weak functions which perform endless loops: __vector_table DCD sfe(CSTACK) DCD Reset_Handler ; Reset Handler DCD NMI_Handler ; NMI Handler DCD HardFault_Handler ; Hard Fault Handler DCD 0 ; Reserved DCD 0 ; Reserved DCD 0 ; Reserved DCD 0 ; Reserved DCD 0 ; Reserved DCD 0 ; Reserved DCD 0 ; Reserved DCD SVC_Handler ; SVCall Handler DCD 0 ; Reserved DCD 0 ; Reserved DCD PendSV_Handler ; PendSV Handler DCD SysTick_Handler ; SysTick Handler Nothing is trigged on debugger side and application looks hanged / stuck. In that case, code break is needed and the PC must be at the address of the Handler. Some IDEs provide the faulty calling code through Call stack window. (Keil® MDK-ARM µVision, SW4STM32). If it is not the case, display registers and find the faulty code address in SP + 0x18 In SW4STM32 all weak default handlers point to the same DefaultHandler which can be confusing. A more efficient approach is to trap the exception by instrumenting Handlers.

6.2 Custom Handlers

One way to generate templates of Handler functions is to use STM32CubeMX. tick boxes as shown in Figure 31. Figure 31. Asking for Handler code generation

  • @brief This function handles Hard fault interrupt.

This simple declaration overriding the default weak function,removes ambiguity and clarifies the call stack. In order to trap the exception, a hardware or a software breakpoint can be set in the IDE or directly programmed in the source code using ARM ® instruction BKPT. Caution: BKPT is not tolerated if no debugger is connected (refer to Chapter 9: From debug to release on page 76). it is advised to set it under #ifdef statement. In-line insertion of assembly instruction in application C code depends on the IDE.

  • IAR™ and SW4STM32 void NMI_Handler(void) #ifdef DEBUG asm ("BKPT 0"); #endif
  • Keil void NMI_Handler(void) #ifdef DEBUG __asm BKPT 0 #endif For each IDE, it is also possible to use the abstraction function defined in the CMSIS library and provided in STM32Cube software pack. void NMI_Handler(void) #ifdef DEBUG __BKPT(0); #endif In all cases, the Halt Debug-Mode is entered; it allows to investigate the issue by inspecting Call Stack and Registers content. Tip: On Keil ® MDK-ARM µVISION, the caller code is not directly accessible in the Call Stack Window. Right clicking "Show Caller Code" as in Figure 32 leads to the faulty line.

Figure 32. Keil® Access to Show Caller Code in Contextual menu

6.3 Trapping div/0 exception

  • Nothing is neither triggered nor trapped.
  • Erroneous returned value generates an unexpected and unpredictable behavior that is very difficult to analyze. This chapter gives several tips in order to properly trap div/0 exceptions.

6.3.1 Cortex ®-M0/M0+ case

breakpoint placed on __aeabi_idiv0() allow to trap the division by zero. offending line in the source code can be rapidly found. To go further refer to section 7.7 of ARM® Compiler Software Development Guide.

6.3.2 Cortex ®-M3/4/7 case

SCB_CCR register description is provided in Figure 33. Figure 33. Cortex®-M3 SCB_CCR Description Refer to STM32F10xxx/20xxx/21xxx/L1xxxx Cortex-M3 programming manual (PM0056). When Div0 occurs it is trapped in HardFault_Handler. SCB_CFSR register description is provided in Figure 34. Figure 34. Cortex-M3 SCB_CFSR Description

through View -> Register -> System Control Block (from Pick List) as shown in Figure 35. Figure 35. IAR™ exception handling

Peripheral -> System Control and Configure. Refer to Figure 36 for details. Figure 36. Keil® System Control and Configure

Figure 37. Keil® Fault Reports

in write mode through: Expression Pane -> Add new expression as shown in Figure 38. Figure 38. SW4STM32 SCB register access

Independently from the IDE, for projects including the CMSIS library, the content of the registers in the code can also be printed: void HardFault_Handler(void) volatile uint32_t csfr= SCB-> CSFR ; // load into variable printf ( "SCB-> CSFR 0x%08x \\n", SCB-> CSFR) // print while (1) The same content can as well be obtained directly from the memory with any memory browser. Other faults like UNALIGNED, UNDEFINSTR can be managed in a similar way. For more details, refer to the relevant programming manual:

  • STM32F10xxx/20xxx/21xxx/L1xxxx Cortex®-M3 programming manual (PM0056)
  • STM32F3, STM32F4 and STM32L4 Series Cortex®-M4 programming manual (PM0214)
  • STM32F7 Series Cortex®-M7 processor programming manual (PM0253) Relevant information is also available on partners websites:
  • https://www.iar.com
  • http://www.keil.com

7 Printf debugging

investigating a non-working system. hardware kits and ecosystem tools.

7.1 STM32 Virtual-COM port driver

most of recent hardware kits (refer to Section 2.1: Hardware development tools on page 9). It is a RS232 emulation through ST-LINK USB connection. Figure 39. Virtual-COM port on Windows® PC

7.2 Printf via UART

USART connected to Virtual-COM port. explains how to use ST-LINK Nucleo stand-alone part as VCP.

  • Nucleo-32/Nucleo-64: USART2 - PA2/PA3
  • Nucleo-144: USART3 - PA9/PA10
  • Discovery: not standard. Refer to the board schematics
  • EVAL: not standard. Refer to the board schematics. Either the VCP or the RS232 connector can be used In STM32CubeMX, for Nucleo board, the VCP USART pins (PA2/PA3) are reserved by default, but required to be enabled by selecting “asynchronous” in USART mode selection box as shown in Figure 40.

Figure 40. USART Pinout configuration with STM32CubeMX -> Parameter Settings as shown in Figure 41.

Figure 41. USART2 setting with STM32CubeMX Retargeting printf to UART depends on the toolchain. For GCC based toolset like SW4STM32, two cases can be met.

STM32F303ZE-Nucleo\\Examples\\UART\\UART_Printf. length 8 with parity require 7 bits + parity on terminal side to match.

7.3 Printf via SWO/SWV

available on Cortex-M3/M4/M7 and supported by the main debugger probes. It is using the ITM (instrumentation trace macrocell) module of the Cortex Core-Sight. STM32 based on Cortex-M3, -M4, and -M7. It is only available if a Serial Wire mode is used. It is not available in JTAG mode. configuration has to be done by the debugger host. Refer to the related chapter of STMicroelectronics reference manual. are strong (alternate function preempting UART GPIOs). Table 5. STM32 USART vs. PC terminal WordLength example

  • PC (Program Counter) sampling
  • Event counters that show CPU cycle statistics
  • Exception and Interrupt execution with timing statistics
  • Trace data - data reads and writes used for timing analysis
  • ITM trace information used for simple printf-style debugging This chapter only addresses the printf-style debugging feature. In order host debugger can manage flexible pin assignment ensure SWO pin is not used for other purpose. In STM32CubeMX: Select "Trace Asynchronous Sw" in SYS -> Debug selection box as shown in Figure 42.

Figure 42. SWO Pin configuration with STM32CubeMX This secures that the PB3 is not allocated to another use. No specific code is generated. Other init steps are performed by the SWV integrated in the IDE or in the ST-LINK utility.

Figure 44. IAR™ SWO Clock setting SWO printf occurrences are visible in Terminal I/O windows. Port Stimulus 0 is used by printf and scanf. It is not configurable. example is given in Figure 45.

  1. Enable ITM Stimulus Port 0

SW4STM32 (and all GCC based toolset) With syscall.c integrated to the project: #include "stdio.h" int __io_putchar(int ch) ITM_SendChar(ch); return(ch); Without syscall, add: int _write(int file, char *ptr, int len) int DataIdx; for (DataIdx = 0; DataIdx < len; DataIdx++) __io_putchar(*ptr++); return len;

be used instead. Figure 47 shows the use of SWV in ST-LINK Utilities. Figure 47. SWV in ST-LINK utility Refer to STM32 ST-LINK utility software description user manual (UM0892) for details. based on their importance (info, debug, error) or there source.

7.4 Semihosting

and use the Input/Output facilities on a host computer that is running a debugger.

instead of having a screen and keyboard on the target system.

  • Semihosting only works during a debug session. Otherwise, the program gets stuck in the first printf() routine reached.
  • Since semihosting uses breakpoint instruction and host dependent code, it has significant and unpredictable impact on performance. Semihosting depends on the library provided by the IDE. The next sections present how to set semihosting using the three main IDEs covered in this application note.

7.4.1 IAR™ EWARM

IAR™ EWARM provides a highly integrated semihosting feature, enabled by default. -> Library Configuration Pane. Figure 48. Semihosting configuration in IAR™

In such a case, simply use printf() / scanf() functions in the code. Input and output of the program are displayed in the Terminal I/O window.

7.4.2 Keil ® MDK-ARM µVISION

Keil® has no semihosting capability.

7.4.3 SW4STM32

SystemWorkbench for STM32 User Guide. Figure 49. Semihosting procedure in SW4STM32

8 Debug through hardware exploration

tools such as oscilloscopes or logic analyzers.

8.1 Easy pinout probing with STMicroelectronics hardware kits

pinout access thanks to their Morpho or Arduino™ connectors. MCU type. In most cases, a large number of GPIOs are covered. that modify the routing of pins to connectors.

8.2 Microcontroller clock output (MCO)

enable measurement through an external tool, typically an oscilloscope. and help to investigate potential error in clock tree initialization code.

8.2.1 Configurati on with STM32CubeMX

Clock Output option in the RCC section as shown in Figure 52. Figure 52. MCO pin selection in STM32CubeMX This allocates a pin labeled RCC_MCO.

Figure 54. MCO Multiplexer in STM32CubeMX Clock Configuration Pane The divider allows to output a signal frequency compatible with output capabilities.

8.2.2 HAL_RCC_MCOConfig

Caution: The setting of GPIO speed (OSPEED) must be carefully set. the related MCU in chapter I/O port characteristics. Max Frequency values are given for a typical load of 50 pF or 10 pF.

The default value in RCC HAL function is the highest (which is good). MX_GPIO_init() function (executed after MCO config) is the lowest. In case the output clock is higher than 1 MHz, it is recommended to change this. oscillation is observed (overshoot / undershoot).

8.2.3 STM32 Series differences

STM32L4x5 and STM32L4x6 advanced ARM®-based 32-bit MCUs (RM035) for details. use and the use of the ST-LINK VCP are mutually exclusive. Refer to the board user manual for details. Figure 55. Refer also to Appendix D: Cortex®-M debug capabilities reminder on page 97.

Figure 55. STM32F4/F7 dual MCO capabilities

From debug to release AN4989

9 From debug to release

It is important to have in mind that most of technics presented in this AN and suitable for debugging have to be properly cleaned to prevent problem while releasing the application. The following action list can be used as a checklist helping to avoid the most common problems:

  • Remove software BKPT instructions or take care to let them inside #ifdef DEBUG statements.
  • Ensure printf() uses available data path on final product. Semihosting and SWO cause hardfault otherwise.
  • Reestablish Code Optimization level.
  • Implement proper Fault Handlers.
  • Reset DBGMCU registers to default.

10 Troubleshooting

debug setting and operation. Table 6. Troubleshooting Ensure SWD pin not set in analog state. Section 4.3: Low-power case. Fail to get printf via SWO Refer to Section 7.3: Printf via SWO/SWV. NRST (e.g. check SB12 for Nucleo). Compiler optimization is probably enabled. Remove it. Refer to Chapter 3: Compiling for debug.

Figure 58. DBGMCU_CR HAL Library Functions Some HAL macros are also available to Enable/Disable this clock. to set DBGMCU registers through debugger interfaces or scripts.

Figure 60. EWARM C-SPY® Macro script setting Debugging Guide available in IAR Help Menu and on www.iar.com.

Figure 61. Accessing DBGMCU register in Keil® MDK-ARM µVision (1/2)

Figure 63. Keil® Initialization script setting

Figure 65. Generator Options debug MCU in SW4STM32 V2.0.0 window as shown in Figure 66.

Figure 66. Runtime R/W access to DBGMCU register with SW4STM32

between MCU and PC to setup a proper serial connection. another serial connection with the PC. appropriate RS232 level shifter. capacity to disconnect on-board ST-LINK from STM32 application part. USB cable is connected. This configuration is presented in As show in Figure 67. Figure 67. ST-LINK cuttable part of Nucleo In this case the ST-LINK part can be used as a stand-alone module.

  1. As debugger interface to program and debug an external application as documented in
  2. As an alternative and/or additional Virtual-COM port

Figure 69. Virtual-COM port on PC side Note: This usage implies to have several targets connected to a single host PC.

among several ones using ST-LINK probe. Each ST-LINK connection is identified by a serial number. In order to correlate a serial number with a board, it is advised to use the ST-LINK utility. Open the setting pane (Target -> Settings). At the top of the screen, the serial number pick list contains all connected ST-LINK probes. LED switch from red to green. Figure 70. ST-LINK utility target selection pick list

Figure 76. Forcing specific ST-LINK S/N with SW4STM32

STM32 families debug capabilities depend on their Cortex®-M type. For more details, refer to the related Cortex® ARM® documentation. Table 7. STM32 Series vs. debug capabilties

  1. Microcontroller Clock Output (refer to Section 8.2: Microcontroller clock output (MCO) on page 71)
  2. Depends on package size. Check availability in the Pin Allocation Table in the related datasheet.

Revision history

Table 8. Document revision history 16-Jun-2017 1 Initial release. 29-Jun-2017 2 Added Table 1: Applicable products.