Tutorial: ARM Cortex-M Series MCU Error Tracking Library CmBacktrace: Simplifying Fault Diagnosis

CmBacktrace Fault Diagnosis

In the world of embedded development, ARM Cortex-M series microcontrollers are widely used in various embedded systems due to their high performance and low power consumption. However, as system complexity increases, developers often feel helpless when facing issues like “Hard Faults.” Quickly locating and resolving these errors has become a significant challenge for developers. Today, we will introduce an open-source project—CmBacktrace, which was created to address this issue.

CmBacktrace (Cortex Microcontroller Backtrace) is an open-source error tracking library specifically designed for ARM Cortex-M series MCUs. It can automatically trace and locate error codes, analyze the causes of errors, and significantly improve the efficiency and accuracy of fault diagnosis. Whether you are a beginner or an experienced developer, CmBacktrace can provide you with strong support, allowing you to focus on your embedded systems without worrying about error localization. Next, we will delve into the features, usage methods of CmBacktrace, and how it helps developers enhance their development efficiency.

Preparation Before Porting

This porting is based on the domestic Yateli Technology AT32MCU, using the CLion + CMake + GCC development environment, which is more modern compared to traditional Keil/IAR, making it suitable for engineers accustomed to Linux/cross-platform development.

Next, we will detail:

Introduction to CmBacktraceAdaptation and Configuration of AT32MCUCompilation and Debugging in CLion+CMake+GCC EnvironmentPractical Case: How to Quickly Locate Faults Using CmBacktrace

Introduction to CmBacktrace

CmBacktrace (Cortex Microcontroller Backtrace) is an open-source library for automatic tracking and localization of error codes, as well as automatic analysis of error causes, specifically for ARM Cortex-M series MCUs. Its main features are as follows:

The main features are as follows:

  • • Supported errors include:
  • Assertions (assert)
  • • Faults (Hard Fault, Memory Management Fault, Bus Fault, Usage Fault, Debug Fault)
  • • Automatic diagnosis of fault causes: It can automatically analyze the cause of the fault and locate the code position where the fault occurred without the need for manual analysis of complex fault registers;
  • • Outputs the function call stack at the time of the error (requires the addr2line tool for precise localization), restoring the scene information at the time of the error, making it quicker and more accurate to locate the problem code. This library can also be used in normal conditions to obtain the current function call stack;
  • • Supports bare-metal and below operating system platforms
  • • UCOS
  • • FreeRTOS (requires source code modification)
  • • RT-Thread
  • • Outputs corresponding thread stack or C main stack based on the fault scene state;
  • • Fault diagnosis information supports multiple languages (currently: Simplified Chinese, English);
  • • Compatible with Cortex-M0/M3/M4/M7 MCUs;
  • • Supports IAR, KEIL, GCC compilers

AT32MCU Project Configuration

This project is based on the ArteryTek AT32F407 series microcontroller GCC + OpenOCD project template, suitable for quickly setting up an embedded development environment.

Project address: https://gitee.com/xcet/embedded-arterytek32-board/tree/master/ref/at32f407-framework

The project structure is clear, containing commonly used peripheral drivers, module drivers, middleware, and application layer examples, facilitating secondary development and functional expansion.

Directory Structure

├── CMakeLists.txt          # CMake build script
├── application/            # Application layer code
│   ├── app_main.c          # Main application source file
│   ├── app_shell.c         # Command line shell application source file
│   ├── app_system.c        # System application source file
│   ├── at32f403a_407_int.c # Interrupt service routine source file
│   ├── button_task.c       # Button task source file
│   ├── xf_app/             # Custom application related files
│   └── xf_config/          # Custom configuration related files
├── bspdrivers/             # Board support package drivers
│   ├── at32f403a_407_clock.c  # Implements system clock configuration function
│   ├── at32f403a_407_conf.h   # Chip configuration header file
│   ├── bsp_core_delay.c       # Implements system delay function configuration
│   ├── bsp_timer.c            # Implements Timer peripheral configuration
│   ├── bsp_uart.c             # Implements UART serial communication peripheral configuration
├── cmake-build-debug/      # CMake debug build directory
├── libraries/              # Library files
│   ├── cmsis/              # ARM Cortex-M microcontroller software interface standard library
│   └── drivers/            # Peripheral driver library
├── middlewares/            # Middleware
│   ├── ....
├── moduledriver/           # Module drivers
│   ├── drv_button.c        # Button driver source file
│   ├── drv_button.h        # Button driver header file
│   ├── drv_led.c           # LED driver source file
│   ├── drv_led.h           # LED driver header file
│   └── lcd/                # LCD driver related files
├── pyocd-flash.txt         # PyOCD programming configuration file
├── pyocd.yaml              # PyOCD configuration file
├── readme.md               # Project documentation
├── tools/                  # Tool files
│   ├── AT32F407xG_FLASH.ld # Linker script
│   ├── AT32F407xx_v2.svd   # System view description file
│   ├── startup_at32f403a_407.s   # ARM assembly startup file (gcc version)
├── clear.bat               # Batch script to clean compilation files

Detailed Explanation of Project Folders

1. application

The application layer code directory stores the main business logic and functionality implementation of the project.

  • <span>app_main.c</span> and <span>app_main.h</span>: The source file and header file for the main application, which is the entry point of the program, responsible for initialization and calling other modules.
  • <span>app_shell.c</span>: Implementation of the command line shell application, which can be used to interact with the system.
  • <span>app_system.c</span> and <span>app_system.h</span>: Related peripherals and overall framework design files.
  • <span>at32f403a_407_int.c</span> and <span>at32f403a_407_int.h</span>: Implementation of the interrupt service routine, handling hardware interrupt events.
  • <span>button_task.c</span> and <span>button_task.h</span>: Implementation of the button task, handling button input events.
  • <span>xf_app/</span> and <span>xf_config/</span>: Files related to custom applications and configurations, which can be expanded according to project needs.

2. bspdrivers

This folder <span>bspdrivers</span> contains the board support package (BSP) driver files for the AT32F407 microcontroller, facilitating developers in configuring and using the chip’s peripherals.

  • <span>at32f403a_407_clock.c</span>: Implements system clock configuration function.
  • <span>bsp_core_delay.c</span>: Provides various delay functions, supporting both DWT (Data Watchpoint and Trace) and SysTick methods for microsecond, millisecond, and second-level delays.
  • <span>bsp_timer.c</span>: Contains functions for timer initialization, interrupt handling, delay, and soft timer management.
  • <span>bsp_uart.c</span>: Implements UART initialization, character and string sending and receiving, and sending different types of values.
  • <span>at32f403a_407_conf.h</span>: Configuration header file for the AT32F403A/407 series chips.

3. libraries

The library files directory contains the libraries that the project depends on.

  • <span>cmsis/</span>: ARM Cortex-M microcontroller software interface standard library, providing a unified hardware abstraction layer and system services.
  • <span>drivers/</span>: Peripheral driver library, containing drivers for various hardware peripherals such as UART, SPI, I2C, Timer, ADC, etc.

4. middlewares

The middleware directory contains various third-party libraries and tools, such as network protocol stacks, file systems, real-time operating systems, etc.

  • cm_backtrace: A crash backtrace component for embedded systems, helping to locate the program crash position.
  • fatfs: A lightweight file system module providing file management functions for embedded devices.
  • freemodbus: Implementation of the Modbus protocol stack for communication between embedded devices.
  • freertos: An open-source real-time operating system kernel widely used in embedded system development.
  • i2c_application: Application code based on the I2C bus, implementing I2C-related functions.
  • lettershell: A lightweight command line shell component, facilitating user interaction with embedded systems.
  • lwip: A lightweight TCP/IP protocol stack suitable for resource-constrained embedded devices.
  • osal: Operating system abstraction layer, providing a unified interface for different operating systems.
  • usb_component: USB-related components for implementing USB functionality in embedded devices.
  • xf_component: Custom components containing modules for logging, buttons, software timers, etc., for project development.

5. moduledriver

The module driver directory contains drivers for commonly used hardware modules.

  • <span>drv_button.c</span> and <span>drv_button.h</span>: Implementation of the button driver, providing button detection and handling functions.
  • <span>drv_led.c</span> and <span>drv_led.h</span>: Implementation of the LED driver, providing LED control functions.
  • <span>lcd/</span>: Files related to the LCD driver, used for driving LCD displays.

6. tools

The tools files directory contains the tool files required for project development and debugging.

  • <span>AT32F407xG_FLASH.ld</span>: Linker script used to specify the memory layout and linking rules of the program.
  • <span>AT32F407xx_v2.svd</span>: System view description file used for debugging tools to identify hardware registers.
  • <span>startup_at32f403a_407.s</span>: ARM assembly startup file (gcc version), used to initialize the hardware environment, set the stack and interrupt vector table after powering on or resetting the AT32F403A/407 chip.
  • <span>at32_dap.cfg</span>: OpenOCD configuration file for configuring debugging and programming operations with the AT32F403A/407 chip via the DAP interface.
  • <span>ArteryTek.AT32F403A_407_DFP.2.2.2.pack</span>: Device family pack containing resources needed for the development of the AT32F403A/407 series chips, for development tools to recognize and support the chip.

Practical Case: How to Quickly Locate Faults Using CmBacktrace

Porting Steps

1. Download the Source Code

https://github.com/armink/CmBacktrace

2. Copy Source Files

Tutorial: ARM Cortex-M Series MCU Error Tracking Library CmBacktrace: Simplifying Fault Diagnosis

  • • Add header files <span>cm_backtrace.h</span>, <span>cmb_cfg.h</span>, <span>cmb_def.h</span>
  • • Add source file <span>cm_backtrace.c</span>
  • • Add demo files to the application folder <span>demos/non_os/stm32f10x/app/src/fault_test.c</span>
  • Tutorial: ARM Cortex-M Series MCU Error Tracking Library CmBacktrace: Simplifying Fault DiagnosisTutorial: ARM Cortex-M Series MCU Error Tracking Library CmBacktrace: Simplifying Fault Diagnosis

3. Modify CMakeLists.txt

Tutorial: ARM Cortex-M Series MCU Error Tracking Library CmBacktrace: Simplifying Fault DiagnosisTutorial: ARM Cortex-M Series MCU Error Tracking Library CmBacktrace: Simplifying Fault Diagnosis

4. Redirect printf

Implement it according to different MCUs

5. Modify the file cmb_cfg.h

/*
 * This file is part of the CmBacktrace Library.
 *
 * Copyright (c) 2016, Armink, &lt;[email protected]&gt;
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * 'Software'), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * Function: It is the configure head file for this library.
 * Created on: 2016-12-15
 */

#ifndef _CMB_CFG_H_
#define _CMB_CFG_H_

#include "xf_dlog.h"

#ifdef    CMB_USER_CFG
#include "cmb_user_cfg.h"
#else
/* print line, must config by user */
#define cmb_println(...)           printf(__VA_ARGS__);printf("\r\n")    /* SEGGER_RTT_printf(0, __VA_ARGS__);SEGGER_RTT_WriteString(0, "\r\n")  */
/* enable bare metal(no OS) platform */
#define CMB_USING_BARE_METAL_PLATFORM
/* #define CMB_USING_BARE_METAL_PLATFORM */
/* enable OS platform */
/* #define CMB_USING_OS_PLATFORM */
/* OS platform type, must config when CMB_USING_OS_PLATFORM is enable */
/* #define CMB_OS_PLATFORM_TYPE           CMB_OS_PLATFORM_RTT or CMB_OS_PLATFORM_UCOSII or CMB_OS_PLATFORM_UCOSIII or CMB_OS_PLATFORM_FREERTOS or CMB_OS_PLATFORM_RTX5 or CMB_OS_PLATFORM_THREADX */
/* cpu platform type, must config by user */
#define CMB_CPU_PLATFORM_TYPE        CMB_CPU_ARM_CORTEX_M4   /* CMB_CPU_ARM_CORTEX_M0 or CMB_CPU_ARM_CORTEX_M3 or CMB_CPU_ARM_CORTEX_M4 or CMB_CPU_ARM_CORTEX_M7 or CMB_CPU_ARM_CORTEX_M33 */
/* enable dump stack information */
#define CMB_USING_DUMP_STACK_INFO
/* #define CMB_USING_DUMP_STACK_INFO */
/* language of print information */
/* #define CMB_PRINT_LANGUAGE             CMB_PRINT_LANGUAGE_ENGLISH(default) or CMB_PRINT_LANGUAGE_CHINESE or CMB_PRINT_LANGUAGE_CHINESE_UTF8 */
#define CMB_PRINT_LANGUAGE     CMB_PRINT_LANGUAGE_ENGLISH
#endif

#endif /* _CMB_CFG_H_ */

6. Modify the ld linker file

Add _stext = .; before the text segment starts.

Tutorial: ARM Cortex-M Series MCU Error Tracking Library CmBacktrace: Simplifying Fault Diagnosis

Add _sstack = .; before the bss segment starts.

Tutorial: ARM Cortex-M Series MCU Error Tracking Library CmBacktrace: Simplifying Fault Diagnosis

7. Comment out the interrupt service functions

Tutorial: ARM Cortex-M Series MCU Error Tracking Library CmBacktrace: Simplifying Fault Diagnosis

8. Call the function

// cm_backtrace exception backtrace component
#include "cm_backtrace.h"
#include "fault_test.h"

#define APPNAME                        "CmBacktrace"
#define HARDWARE_VERSION               "V1.0.0"
#define SOFTWARE_VERSION               "V0.06.08"


staticvoidComponent_Init(void)
{
    #if USE_LETTER_SHELL
        shell_usart_init();
    #endif

    #if  USE_CM_BACKTRACE  // Enable macro definition to use cm_backtrace component
    cm_backtrace_init(APPNAME, HARDWARE_VERSION, SOFTWARE_VERSION);
    #endif
}

// Main function calls 
        fault_test_by_unalign();
        fault_test_by_div0();   

9. Compile and Download the Program

Tutorial: ARM Cortex-M Series MCU Error Tracking Library CmBacktrace: Simplifying Fault Diagnosis

Code after compilation error:

Tutorial: ARM Cortex-M Series MCU Error Tracking Library CmBacktrace: Simplifying Fault Diagnosis

Convert to localization code tool:

Tutorial: ARM Cortex-M Series MCU Error Tracking Library CmBacktrace: Simplifying Fault Diagnosis

Open the terminal and enter the following command

addr2line -e at32f407.elf -afpiC 08001d9c 08001d9c 08001b30 08004c74 08001b52 080018ca 08005546
Tutorial: ARM Cortex-M Series MCU Error Tracking Library CmBacktrace: Simplifying Fault Diagnosis

Reference Documents

  1. 1. Configuring CLion for STM32 Development 【Elegant Embedded Development】https://zhuanlan.zhihu.com/p/145801160
  2. 2. Sky Star Development Board Environment Setup Tutorial and Template https://gitee.com/lcsc/skystar-board-templates
  3. 3. CmBacktrace Porting https://xuan9527.github.io/2024/04/19/CmBacktrace%E7%A7%BB%E6%A4%8D/
  4. 4. ARM Cortex-M Series MCU Error Tracking Library https://github.com/armink/CmBacktrace

Leave a Comment