Electrical – How to handle configuration changes to the project with STM32CubeMX


Just starting to use STM32CubeMX and Atollic TrueSTUDIO to code for STM32L011.

One thing I noticed is that if I made any changes to the project configuration in STM32CubeMX – they will automatically appears in the main.c file without damaging to the code that I added to the main.c beforehand.

However this can not be applied to auxilary files, like system_stm32l0xx.c in my case where I wanted to put my ADC interrupt service routine.

My questions are:

  • How to protect my code from changing after I made the changes with STM32CubeMX?
  • Why is there a different behaviour with main.c and auxilary files?
  • Is there a better way to handle changes to the project configuration with STM32CubeMX? May be I need to split up the project into more files?

Best Answer

system_stm32l0xx.c has no /* USER CODE BEGIN ... */ - /* USER CODE END ... */ blocks in it, you are not supposed to put user code in that file. Put it somewhere else. Is there any reason why your interrupt handler should live in the same file as the clock setup code?

There is a designated place for interrupt handlers in stm32l0xx_it.c, see the comments at the top

* @file    stm32l0xx_it.c
* @brief   Interrupt Service Routines.

and at the bottom

/* STM32L0xx Peripheral Interrupt Handlers                                    */
/* Add here the Interrupt Handlers for the used peripherals.                  */
/* For the available peripheral interrupt handler names,                      */
/* please refer to the startup file (startup_stm32l0xx.s).                    */



You can let CubeMX generate an interrupt handler for you (in the NVIC Settings tab of the peripheral configuration pane), it that case it will appear in stm32l0xx_it.c, and there will be user code blocks before and after the call to the HAL handler. (Put an if(0) in the last line of the user block preceding the call to HAL_ADC_IRQHandler(&hadc) if you don't want to call the HAL handler.)

If you don't want to have the interrupt managed by CubeMX, then you can put the handler in any user code block outside functions, or in a separate source file which is not managed by CubeMX.