Why are MSPs defined as callback functions?

590 Views Asked by At

In STM32CubeMX MSP stands for MCU Support Package and of all here is what it basically about:

MSPs are user callback functions to perform system level initializations such as (Clock, GPIOs, DMA, interrupts).

Now I'm looking at such a function used as:

HAL_TIM_MspPostInit(&htim2);

And when I open declaration it is found under stm32f3xx_hal_msp.c as:

void HAL_TIM_MspPostInit(TIM_HandleTypeDef* htim)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};
  if(htim->Instance==TIM2)
  {
  /* USER CODE BEGIN TIM2_MspPostInit 0 */

  /* USER CODE END TIM2_MspPostInit 0 */

    __HAL_RCC_GPIOA_CLK_ENABLE();
    /**TIM2 GPIO Configuration
    PA0     ------> TIM2_CH1
    */
    GPIO_InitStruct.Pin = GPIO_PIN_0;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
    GPIO_InitStruct.Alternate = GPIO_AF1_TIM2;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /* USER CODE BEGIN TIM2_MspPostInit 1 */

  /* USER CODE END TIM2_MspPostInit 1 */
  }

Now in C callback function is a function which its pointer is passed to another function. Here selected answer is an example.

My question is: What makes MSPs callback functions? They get structs passed as arguments not functions. And where are the callbacks in MSPs? I could not see the footprint of a callback function there. An example would help.

2

There are 2 best solutions below

2
On

A callback means a function in the application code which is called by library code.

In this case your application code tells the library code "I want to initialize timer TIM2". The library code does part of the job, then it gets to the bit where it has to configure the pinout (which the timer library has no knowledge of) so it calls back to the application code to do the pin setup. When the MSP function returns the timer library code completes setting up the timer and returns to the application.

For the sake of simplicity the name of the callback function is hard coded into the library function, and so it ends up linked statically. This avoids the need for a function pointer. It is the flow of control back to application code before the library function has returned which makes this a callback, not the language syntax used.

2
On

These function are called by HAL library. (Like HAL_TIM_Init in your case) These are necessary to split the generic library from your implementation/mp. Its an hardware abstraction layer library after all.

Most of these HAL callback function have weak implementation so even if you don't define them there always an empty implementation provided by the library to make sure your code compiles.