How to read multichannel ADC in STM32

THIS MIGHT NOT WORK WITH THE NEWER CUBEMX VERSIONS. CHECK OUT THE UPDATED METHOD HERE

I have already posted articles about ADC in STM32 using PollforConersion, Interrupt and DMA methods. But in all those articles, I used single channel of the ADC. So today We will see How to read multichannel ADC in STM32.

The process remains same as using in single channel, with some addons though. Let’s get into it

First we need to set up the channels, we want to read, under ADC. Here I will read Channels 0, 1 and internal temperature sensor (16).

ADC Channels

1.) USING PollforConversion Method

With the new firmware, it’s not possible to use the PollforConversion directly. I have written a tutorial where we can modify the pregenerated functions to make it possible. Check that out https://controllerstech.com/stm32-adc-multi-channel-without-dma/


2.) USING DMA METHOD

To use DMA, we need to enable the DMA continuous request in the ADC configuration. Also enable the interrupt and setup the DMA as shown below->

Enable DMA request
Enable interrupt
Setup DMA in circular mode

Generate the project and open it.

uint32_t adc[3], buffer[3], temperature;  // define variables
float vsense = 3.3/1023;

Now we have to write a conversion complete function. It will be called whenever the conversion of the ADC values is completed.

void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
{
	for (int i =0; i<3; i++)
	{
	   adc[i] = buffer[i];  // store the values in adc[]
	}

        temperature = (((adc[2]*vsense)-.76)/.0025)+25;
}

Start the ADC in DMA mode in the main function.

HAL_ADC_Start_DMA(&hadc1, buffer, 3);

As to show that it works completely independent, I will blink a LED inside the while loop and the ADC values will be received separately from the while loop.

while (1)
{
  HAL_GPIO_TogglePin (GPIOA, GPIO_PIN_5);
  HAL_Delay (1000);
}

THIS code is for DMA method

CHECK OUT THE UPDATED METHOD HERE

uint32_t adc[3], buffer[3], temperature;
float vsense = 3.3/1023;

void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
{
	for (int i =0; i<3; i++)
	{
	  adc[i] = buffer[i];
	}

	temperature = (((adc[2]*vsense)-.76)/.0025)+25;
}	

int main(void)
{
  HAL_Init();

  SystemClock_Config();

  MX_GPIO_Init();
  MX_DMA_Init();
  MX_ADC1_Init();

	HAL_ADC_Start_DMA(&hadc1, buffer, 3);

  while (1)
  {

	HAL_GPIO_TogglePin (GPIOA, GPIO_PIN_5);
	HAL_Delay (1000);

  }

}

Result

Check out the VIDEO Below


. . . . . DOWNLOAD . . . . .

You can buy me a coffee Sensor by clicking DONATE OR Just click DOWNLOAD to download the code

controllerstech
100%
100%
Subscribe
Notify of
guest
20 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Menu