cancel
Showing results for 
Search instead for 
Did you mean: 

STM32 dual channel ADC

MS.23
Associate II

I am trying to read ADC from two channels without using DMA. For that I use this code:

 

/* USER CODE BEGIN 0 */
uint16_t ADC_VAL[2];

void ADC_Select_CH1(void)
{
    ADC_ChannelConfTypeDef sConfig = {0};
 
    sConfig.Channel = ADC_CHANNEL_0;
    sConfig.Rank = ADC_REGULAR_RANK_1;
    sConfig.SamplingTime = ADC_SAMPLETIME_1CYCLE_5;
    if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
    {
      Error_Handler();
    }
}

void ADC_Select_CH2(void)
{
    ADC_ChannelConfTypeDef sConfig = {0};
 
    sConfig.Channel = ADC_CHANNEL_1;
    sConfig.Rank = ADC_REGULAR_RANK_2;
    if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
    {
      Error_Handler();
    }
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* Configure the system clock */
  SystemClock_Config();

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART2_UART_Init();
  MX_ADC1_Init();

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
          //1st channel ADC conversion
          ADC_Select_CH1();
          HAL_ADC_Start(&hadc1);
          HAL_ADC_PollForConversion(&hadc1, 1000);
          ADC_VAL[0] = HAL_ADC_GetValue(&hadc1);
          HAL_ADC_Stop(&hadc1);
 
          //2nd channel ADC conversion
          ADC_Select_CH2();
          HAL_ADC_Start(&hadc1);
          HAL_ADC_PollForConversion(&hadc1, 1000);
          ADC_VAL[1] = HAL_ADC_GetValue(&hadc1);
          HAL_ADC_Stop(&hadc1);
  }
  /* USER CODE END 3 */
}
 
This code works perfectly for NUCLEO-L433RC-P and NUCLEO-L476RG, but it doesn't work on NUCLEO-F103RB. I would like to know why is that. On F103RB board first ADC channel shows correct readings and second channel just shows the same value as first channel.
1 ACCEPTED SOLUTION

Accepted Solutions
TDK
Guru

> sConfig.Rank = ADC_REGULAR_RANK_2;

If you're only converting a single channel, this should be ADC_REGULAR_RANK_1.

> sConfig.SamplingTime = ADC_SAMPLETIME_1CYCLE_5

Consider increasing this. Also, you should initialize it in your ADC_Select_CH2 function, otherwise it will have an undefined value.

If you feel a post has answered your question, please click "Accept as Solution".

View solution in original post

1 REPLY 1
TDK
Guru

> sConfig.Rank = ADC_REGULAR_RANK_2;

If you're only converting a single channel, this should be ADC_REGULAR_RANK_1.

> sConfig.SamplingTime = ADC_SAMPLETIME_1CYCLE_5

Consider increasing this. Also, you should initialize it in your ADC_Select_CH2 function, otherwise it will have an undefined value.

If you feel a post has answered your question, please click "Accept as Solution".