Programming - Framework

Created:2018-01-19  Last modified:2018-01-20


  1. Introduction

    Programming in the relatively complicated 32-bit Cortex-M devices is different from the 8-bit Atmege AVR microcontrollers. Because STM32 deivces have more registers, those registers are 32-bit long instead of 8-bit, and it has more functions, such as DMA, programming by directly accessing registers is not recommended. Moreover, it is difficult to run the code in different microcontrollers (bad portablity). Therefore, programming STM32 and other cortex-m devices are usually via well-defined libraries.

    C provides a good trade-off between coding efficiency, protability, execution effciency and code size.

    Moreover, Cortex-M3 support different operating modes, priviledge/unprivileged instruction, and two stack pointer, which means it has some hardware support for a operating system. Then programming style can treat this device as a simple MCU that does not have those features, or play with those features and perphaps with a RTOS. In this note, the device is programmed as a simple MCU that only uses the main stack.

    The libraries used to program a STM32 and other cortex-M device are organized as a layered architecture.

    Pros and Cons about the layered architecture

    1. + hide complexity
    2. + modularity (good for portable)
    3. - calling overhead: have to go through each layer.

    Layers in programming stm32

    1. mbed-os (provided by mbed (ARM), a suite of API, such as Ethernet, GPIO, ...)
    2. mbed HAL (collaborated by mbed (ARM) and vendor, defines a hardware abstraction layer to hide the difference of devices' configuration)
    3. STM32 Core + HAL lib (provided by ST, defines the peripherals registers (e.g. GPIO, flash), data structure
    4. CMSIS (provided by ARM, defines the registers of the core, interrupts, data structure, compiling convention... e.g. core_cm3.h

    As a developer, we can start from any layer.

  2. Framework

    STM32 Core + HAL lib

    Using HAL lib is optional, the header file structure is shown below

    1. Using HAL is optional, but it is often used because it defines the clock and a few necessary registers. To include the HAL, define the macro "USE_HAL_DRIVER"
    2. stm32f1xx_hal_conf.h is a configuration file that determine which HAL device would be included. Uncomment the defined macro to select the desired peripherals
    3. stm32f1xx.h defines few common structures and includes the correct device header file Define macro STM32F103xB
    4. system_stm32f1xx.h/.c defines two functions
      1). SystemInit() is called before main (shown in the startup .S file) to reset clock.
      2). SystemCoreClockUpdate()
    5. core_cm3.h defines the used cmsis version and compiler such as armcc, gnu_gcc, icc_arm.
    6. core_cmInstr.h/core_cmFunc.h choose the correct pre-defined inline assembly code.
    7. cmsis_armcc.h defines the inline assembly for armcc compiler.