STM32 ADC MULTI CHANNEL WITHOUT DMA
In the past I have covered ADC Multiple channels in STM32 with DMA. Although, the process was fine and DMA works pretty good, users were experiencing the problem with the while loop. Some users reported that the while loop never runs, and they were correct too. When the ADC channel frequency is high, the DMA interrupts gets triggered very often and the control always remains in the callback function, and the while loop remains inactive forever.
So I have decided to write this tutorial, in which I will cover the multiple channels but without the use of DMA. Although with the new CubeMX this is not an option by default, so we will modify some inbuilt functions. This will not only solve the problem with the while loop, but it will also let you use any channel of ADC at any point in the code.
Basically, you do the conversion of whatever channel you want, and whenever you want.
The ADC Setup is shown below
- I have selected 3 channels i.e CHANNEL 0, CHANNEL 1 and the TEMP SENSOR CHANNEL.
- Since we are using multiple channels, we need to enable the Scan Conversion Mode
- I have also enabled the Continuous Conversion, it’s not needed though. You can disable it if you want
- As I am using 3 channels, select the Rank as 3
- I have set the different Sampling Time for each channel here
That’s all for the CubeMX setup. Now let’s see the code
Some Insight into the code
First of all we will modify the generated ADC_INIT function as shown below
- I have commented the lines 31-57, so the channels can not be configured in the beginning. Also copy these, since we will write separate functions and paste them there
- Notice that in line no 24, I have changed the number of conversions to 1, which was 3 by default
- In the above code, I have create 3 functions for selecting 3 channels of ADC
- I have only copied the respective code in each channel
- Also make sure that the rank of each channel is set to 1 (lines 7, 21,35)
Now in the while loop, we perform the following operations
- Select the channel you want to convert
- Start the ADC
- Poll for the conversion to complete
- Get the ADC Value
- Stop the ADC
This is basically all. So whenever you need to convert a channel, you follow the set of steps (line 7 – line 11), and for the rest of the time, you can continue with any other operation.
You can see above that all the 3 channels of ADC shows different values. To see the full working, check the video below