cancel
Showing results for 
Search instead for 
Did you mean: 

If i want to change pulse width on ONE timer pwm channel, do i have to rewrite ALL active channels every time i change one?

KSkor.1
Associate III

I am using one timer (timer2) as pwm generator and i am using 3 channels on it. I wish to set each channel pulse width independently (they are controlling LEDs) from 1 to 100. But from the generated stcubeIDE function, it looks like that the channels pulse width are written sequentially so every time i wish to change one, i need to write other 2, in order. Is that true?

P.S. The MCU i use is STM32L031F6P6.

Below is generated timer function:

static void MX_TIM2_Init(void)
{
 
  /* USER CODE BEGIN TIM2_Init 0 */
 
  /* USER CODE END TIM2_Init 0 */
 
  TIM_ClockConfigTypeDef sClockSourceConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};
  TIM_OC_InitTypeDef sConfigOC = {0};
 
  /* USER CODE BEGIN TIM2_Init 1 */
 
  /* USER CODE END TIM2_Init 1 */
  htim2.Instance = TIM2;
  htim2.Init.Prescaler = 40;
  htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim2.Init.Period = 100;
  htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim2) != HAL_OK)
  {
    Error_Handler();
  }
  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_TIM_PWM_Init(&htim2) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sConfigOC.OCMode = TIM_OCMODE_PWM1;
  sConfigOC.Pulse = 30;
  sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
  sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
  if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
  {
    Error_Handler();
  }
  sConfigOC.Pulse = 50;
  if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
  {
    Error_Handler();
  }
  sConfigOC.Pulse = 60;
  if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_3) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM2_Init 2 */
 
  /* USER CODE END TIM2_Init 2 */
  HAL_TIM_MspPostInit(&htim2);
 
}

1 ACCEPTED SOLUTION

Accepted Solutions
KnarfB
Principal III

You can set the 4 channel compare values independently on-the-fly. Use the __HAL_TIM_SET_COMPARE HAL macro for that as in

__HAL_TIM_SET_COMPARE(&htim3, TIM_CHANNEL_2, pwm2 );

hth

KnarfB

View solution in original post

2 REPLIES 2
KnarfB
Principal III

You can set the 4 channel compare values independently on-the-fly. Use the __HAL_TIM_SET_COMPARE HAL macro for that as in

__HAL_TIM_SET_COMPARE(&htim3, TIM_CHANNEL_2, pwm2 );

hth

KnarfB

KSkor.1
Associate III

Thank you a lot for quick answer and solution.