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
First of all we will modify the generated ADC_INIT function as shown below
- I have commented Out the part where the channels gets configured.
- So the channels can not be configured in the beginning.
- Also copy these, since we will write separate functions and paste them there
- Also mekae sure to change the number of conversions to 1, which was 3 by default (
hadc1.Init.NbrOfConversion = 1)
- In the above code, I have created 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 (
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
- #Modbus 1. STM32 Master Reads Holding and Input Registers October 1, 2022
- MODBUS PROTOCOL 101 September 29, 2022
- RS485 Module and STM32 September 23, 2022
- FDCAN in Normal Mode || STM32H7 September 15, 2022
- STM32 FDCAN in Loopback Mode August 19, 2022
- I2C in ESP32 || ESP-IDF || LCD 1602 July 15, 2022