on
2021-10-06
12:40 AM
- edited on
2025-08-04
2:20 AM
by
Laurids_PETERSE
Some applications require periodic sampling of analog signals using an ADC (Analog to Digital Converter) for digital signal processing. The objective of this article is to explain how to configure an STM32 Timer to trigger ADC conversions at a configurable sampling frequency. A GPIO pin will be toggled with every ADC conversion to show that the sampling is at the expected frequency.
Some applications require periodic sampling of analog signals using an ADC (Analog to Digital Converter) for digital signal processing. The objective of this article is to explain how to configure an STM32 Timer to trigger ADC conversions at a configurable sampling frequency. A GPIO pin will be toggled with every ADC conversion to show that the sampling is at the expected frequency.
STM32CubeIDE, by default, will initialize a GPIO for the on-board green LED (PB0).
Please change “Pin Context Assignment” to ARM Cortex-M7 as shown in the screenshot below.
Make sure the configuration of PB0, which is the GPIO being used is configured as follows:
/* USER CODE BEGIN PV */ uint32_t adc_val; /* USER CODE END PV */
/* USER CODE BEGIN 2 */ // calibrate ADC for better accuracy and start it w/ interrupt if(HAL_ADCEx_Calibration_Start(&hadc1, ADC_CALIB_OFFSET, ADC_SINGLE_ENDED) != HAL_OK) Error_Handler(); if(HAL_ADC_Start_IT(&hadc1) != HAL_OK) Error_Handler(); // start pwm generation if(HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_1) != HAL_OK) Error_Handler(); /* USER CODE END 2 */
/* USER CODE BEGIN 4 */ void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc) { adc_val = HAL_ADC_GetValue(&hadc1); // Toggle the Green LED HAL_GPIO_TogglePin(LD1_GPIO_Port, LD1_Pin); } /* USER CODE END 4 */
Now compile and flash the code to your Nucleo board, reset the board to run the code.
The Green LED is toggling every 100 us indicating the ADC is sampling at the desired 10 KHz rate.
Here is an oscilloscope capture that shows the Green LED GPIO toggling at the desired rate:
In this video we discuss the different steps that were covered in this article:
Hands-On with STM32 Timers: Trigger Periodic ADC Conversions - YouTube
Can you post the code? I followed this tutorial but didn't work :(
Forget it, I have found in "Hands-On with STM32 Timers: Trigger Periodic ADC Conversions - YouTube"
Is it possible to adapt to ADC convert directly to DMA?