Skip to main content
Associate II
July 2, 2024
Solved

Potential bug source in the code generated by CubeMX for components with shared clocks ?

  • July 2, 2024
  • 1 reply
  • 838 views

Hello,

I think I might have found a bug source in the CubeMX's generated code, when two components of a same driver share the same clock.

Here I'll use the example of the ADC 1 and 2 of the STM32H743GTV6 but I have see this case a few times elsewhere.

As the two ADC use the same clock, to avoid initiating it while the other is already using it, a check variable is used:

 

static uint32_t HAL_RCC_ADC12_CLK_ENABLED=0;

void HAL_ADC_MspInit(ADC_HandleTypeDef* adcHandle)
{

 GPIO_InitTypeDef GPIO_InitStruct = {0};
 if(adcHandle->Instance==ADC1)
 {
 /* USER CODE BEGIN ADC1_MspInit 0 */

 /* USER CODE END ADC1_MspInit 0 */
 /* ADC1 clock enable */
 HAL_RCC_ADC12_CLK_ENABLED++;
 if(HAL_RCC_ADC12_CLK_ENABLED==1){
 __HAL_RCC_ADC12_CLK_ENABLE();
 }
 
 /* Some code */

 }
 else if(adcHandle->Instance==ADC2)
 {
 /* USER CODE BEGIN ADC2_MspInit 0 */

 /* USER CODE END ADC2_MspInit 0 */
 /* ADC2 clock enable */
 HAL_RCC_ADC12_CLK_ENABLED++;
 if(HAL_RCC_ADC12_CLK_ENABLED==1){
 __HAL_RCC_ADC12_CLK_ENABLE();
 }

 /* Rest of the function */
 }
}

 

 

And the same thing is done is the void HAL_ADC_MspDeInit(ADC_HandleTypeDef* adcHandle) function:

 

 HAL_RCC_ADC12_CLK_ENABLED--;
 if(HAL_RCC_ADC12_CLK_ENABLED==0){
 __HAL_RCC_ADC12_CLK_DISABLE();
 }

 

But in the case where HAL_ADC_MspDeInit is called before HAL_ADC_MspInit, the HAL_RCC_ADC12_CLK_ENABLED (initiated to 0) will be 0xFFFF FFFF and so the init won't work.

I think something like that would be enough:

 

 if(HAL_RCC_ADC12_CLK_ENABLED!=0){
 HAL_RCC_ADC12_CLK_ENABLED--;
 if(HAL_RCC_ADC12_CLK_ENABLED==0){
 __HAL_RCC_ADC12_CLK_DISABLE();
 }
 }

 

Best regards,

Sulian

Best answer by Pavel A.

Yes this is a known issue but a more complicated solution would be er... more complicated. So in the end, the developer is responsible to find a satisfying solution.

1 reply

Pavel A.
Pavel A.Best answer
Super User
July 2, 2024

Yes this is a known issue but a more complicated solution would be er... more complicated. So in the end, the developer is responsible to find a satisfying solution.