1K
#include "main.h" /* USER CODE BEGIN PV */ uint16_t ADC_VAL = 0 ; /* USER CODE END PV */ /* USER CODE BEGIN 0 */ void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc) { //callBacK IT if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_1)==GPIO_PIN_SET) { //Read and update the ADC Result ADC_VAL = HAL_ADC_GetValue(&hadc1); } //CallBack DMA else if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_2)==GPIO_PIN_SET) { // Conversion complete and DMA Transfer as well //=> Update the PWM Duty Cycle whit the last ADC Conversion Result TIM2->CCR2 = (ADC_VAL<<4); } } /* USER CODE END 0 */ int main(void) { HAL_Init(); SystemClock_Config(); MX_GPIO_Init(); MX_DMA_Init(); MX_ADC1_Init(); MX_TIM2_Init(); /* USER CODE BEGIN 2 */ HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_2); //Calibrate the ADC on Power-up for better Accuracy HAL_ADCEx_Calibration_Start(&hadc1); /* USER CODE END 2 */ while (1) { //Polling Mode if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_0)==GPIO_PIN_SET) { HAL_ADC_Start(&hadc1); //Start ADC Conversion HAL_ADC_PollForConversion(&hadc1, 1);//Poll ADC1 and Timeout =1mSec ADC_VAL = HAL_ADC_GetValue(&hadc1); // Read the ADC Conversion Result TIM2->CCR2 = (ADC_VAL<<4); HAL_Delay(1); } //IT Mode else if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_1)==GPIO_PIN_SET) { HAL_ADC_Start_IT(&hadc1); //Start ADC Conversion IT TIM2->CCR2 = (ADC_VAL<<4);//update PWM Duty Cycle whit the latest Conversion HAL_Delay(1); } //DMA Mode else if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_2)==GPIO_PIN_SET) { HAL_ADC_Start_DMA(&hadc1, (uint32_t*)&ADC_VAL, 1); //Start ADC Conversion DMA HAL_Delay(1); } else{ HAL_ADC_Stop(&hadc1); HAL_ADC_Start_IT(&hadc1); HAL_ADC_Stop_DMA(&hadc1); } } /* USER CODE END 3 */ }