cancel
Showing results for 
Search instead for 
Did you mean: 

How to update TIM4 PWM duty cycle?

EEuge
Senior

Hello!

I have STM32H743B

I configure TIM4 to PWM GEneration

static void MX_TIM4_Init(void)
{
 
  /* USER CODE BEGIN TIM4_Init 0 */
 
  /* USER CODE END TIM4_Init 0 */
 
  TIM_MasterConfigTypeDef sMasterConfig = {0};
  TIM_OC_InitTypeDef sConfigOC = {0};
 
  /* USER CODE BEGIN TIM4_Init 1 */
 
  /* USER CODE END TIM4_Init 1 */
  htim4.Instance = TIM4;
  htim4.Init.Prescaler = 0;
  htim4.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim4.Init.Period = 65535;
  htim4.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim4.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_PWM_Init(&htim4) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim4, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sConfigOC.OCMode = TIM_OCMODE_PWM1;
  sConfigOC.Pulse = 0xFFFF;
  sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
  sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
  if (HAL_TIM_PWM_ConfigChannel(&htim4, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM4_Init 2 */
 
  /* USER CODE END TIM4_Init 2 */
  HAL_TIM_MspPostInit(&htim4);
 
}

I try to change duty cycle

void SetBacklightBrightness(uint16_t brightness) 	
{
	
 
	sConfigOC.OCMode = TIM_OCMODE_PWM1;
  sConfigOC.Pulse = brightness<<8;
		sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
  sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
  if (HAL_TIM_PWM_ConfigChannel(&htim4, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
  {
		Error_Handler();
  }
			
}	

but duty cycle not updates...

How to solve this problem?

1 ACCEPTED SOLUTION

Accepted Solutions

I found solution.

function HAL_TIM_PWM_ConfigChannel resets CCER register.

After adding to code "TIM4->CCER=0x00000010;" problem was solved.

Thanks!

View solution in original post

3 REPLIES 3
KnarfB
Principal III

There is a HAL macro __HAL_TIM_SET_COMPARE just for changing that single register. Not tried on H7 though.

hth

KnarfB

I found solution.

function HAL_TIM_PWM_ConfigChannel resets CCER register.

After adding to code "TIM4->CCER=0x00000010;" problem was solved.

Thanks!

I use for change directly for example

TIM4->CCR2+=50;