Bad code generation with ADC LL API and STM32CubeIDE
I recently changed the configuration of working product from HAL API to LL API to improve performances.
Unfortunately, the LL initialisation code generated by the STM32CubeIDE for the ADC was incomplete, and forgets to set the PCSEL register when needed, resulting in the ADC converter just generating random numbers.
By comparing the registers with the 2 initialisation methods, I found the solution by adding LL_ADC_SetChannelPreselection() when needed.
Below is the code generated by the IDE, and with the 2 missing calls added (after the BUG: comment)
Note: the LL_ADC_SetChannelPreselection() calls should NOT be added when using analog only pads, like PA0_C, PA1_C, PC2_C, PC3_C. However, for general I/O pads, if LL_ADC_SetChannelPreselection() is missing, then the ADC just convert noise.
/** Configure Regular Channel
*/
LL_ADC_REG_SetSequencerRanks(ADC2, LL_ADC_REG_RANK_1, LL_ADC_CHANNEL_12);
LL_ADC_SetChannelSamplingTime(ADC2, LL_ADC_CHANNEL_12, LL_ADC_SAMPLINGTIME_8CYCLES_5);
LL_ADC_SetChannelSingleDiff(ADC2, LL_ADC_CHANNEL_12, LL_ADC_SINGLE_ENDED);
/** Configure Regular Channel
*/
LL_ADC_REG_SetSequencerRanks(ADC2, LL_ADC_REG_RANK_2, LL_ADC_CHANNEL_13);
LL_ADC_SetChannelSamplingTime(ADC2, LL_ADC_CHANNEL_13, LL_ADC_SAMPLINGTIME_8CYCLES_5);
LL_ADC_SetChannelSingleDiff(ADC2, LL_ADC_CHANNEL_13, LL_ADC_SINGLE_ENDED);
/* USER CODE BEGIN ADC2_Init 2 */
/* BUG: these two calls are missing from code generated by the STM32CubeIDE */
LL_ADC_SetChannelPreselection(ADC2, LL_ADC_CHANNEL_12);
LL_ADC_SetChannelPreselection(ADC2, LL_ADC_CHANNEL_13);
/* USER CODE END ADC2_Init 2 */
