Skip to main content
March 7, 2021
Solved

How to update TIM4 PWM duty cycle?

  • March 7, 2021
  • 3 replies
  • 1186 views

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?

This topic has been closed for replies.
Best answer by

I found solution.

function HAL_TIM_PWM_ConfigChannel resets CCER register.

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

Thanks!

3 replies

KnarfB
Super User
March 7, 2021

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

hth

KnarfB

Best answer
March 7, 2021

I found solution.

function HAL_TIM_PWM_ConfigChannel resets CCER register.

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

Thanks!

MM..1
Super User
March 7, 2021

I use for change directly for example

TIM4->CCR2+=50;