Docs

Micro-controllers, wireless transmission and database

Head

RGB LED. Multi channel ADC using STM32CubeIDE

Prerequisites

This project assumes you have already installed STM32CubeIDE. You need to have previously done a basic blink sketch with blue-pill using STM32CubeIDE. I have made a complete video from installing STM32CubeIDE to LED blink program. You can watch it by clicking this link. https://www.youtube.com/watch?v=kXg467nVd_A

Wiring Diagram

Diagram

Image

STM32CubeIDE Settings

ADC1 - IN7, IN8 and IN9 (tick)

Parameter Settings --> ADC Settings --> Continuous Conversion Mode (Enabled)

Click Timer → Click TIM2 →

Clock Source set to Internal Clock

Channel2 set to PWM Generation CH2

Channel3 set to PWM Generation CH3

Channel4 set to PWM Generation CH4

Configuration → Parameter Settings →

Prescaler set to 127

Counter Period 625

Additional code on top of STM32CubeIDE generated code

/* USER CODE BEGIN PV */
uint16_t readValue1;
uint16_t readValue2;
uint16_t readValue3;
uint16_t PWM1;
uint16_t PWM2;
uint16_t PWM3;
ADC_ChannelConfTypeDef sConfigPrivate = {0};
/* USER CODE END PV */

  /* USER CODE BEGIN 2 */
  HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_2);
  HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_3);
  HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_4);
  /* USER CODE END 2 */

  /* USER CODE BEGIN WHILE */
  while (1)
  {
	  sConfigPrivate.Rank = ADC_REGULAR_RANK_1;
	  sConfigPrivate.SamplingTime = ADC_SAMPLETIME_1CYCLE_5;
	  sConfigPrivate.Channel = ADC_CHANNEL_9;
  	  HAL_ADC_ConfigChannel(&hadc1, &sConfigPrivate);
	  HAL_ADC_Start(&hadc1);
	  HAL_ADC_PollForConversion(&hadc1,1000);
	  readValue1 = HAL_ADC_GetValue(&hadc1);
	  HAL_ADC_Stop(&hadc1);
	  sConfigPrivate.Channel = ADC_CHANNEL_8;
	  HAL_ADC_ConfigChannel(&hadc1, &sConfigPrivate);
	  HAL_ADC_Start(&hadc1);
	  HAL_ADC_PollForConversion(&hadc1,1000);
	  readValue2 = HAL_ADC_GetValue(&hadc1);
	  HAL_ADC_Stop(&hadc1);
	  sConfigPrivate.Channel = ADC_CHANNEL_7;
	  HAL_ADC_ConfigChannel(&hadc1, &sConfigPrivate);
	  HAL_ADC_Start(&hadc1);
	  HAL_ADC_PollForConversion(&hadc1,1000);
	  readValue3 = HAL_ADC_GetValue(&hadc1);
	  HAL_ADC_Stop(&hadc1);
	  PWM1 = readValue1/7;
	  PWM2 = readValue2/7;
	  PWM3 = readValue3/7;
	  __HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_2, PWM1);
	  __HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_3, PWM2);
	  __HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_4, PWM3);
	  HAL_Delay(10);
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */