Skip to main content
Graduate
April 19, 2023
Question

STM32G4 PWM. Changing period and duty cycle.

  • April 19, 2023
  • 4 replies
  • 2203 views

Why are no HAL APIs changing the pulse period and duty cycle? Only init, start and stop are available. If we need to change the period and duty cycle how one can achieve this?

    This topic has been closed for replies.

    4 replies

    Graduate
    April 19, 2023

    There are HAL calls for this, but register access is easier/shorter to write, read and understand - just do:

    TIM3->ARR = new_period - 1;
    TIM3->CCR2 = new_duty;

    Graduate
    April 19, 2023

    Hi @gbm​ can you please point out which HAL APIs are used to alter the period and duty cycle? I am using HAL for controlling. It would be easier for me.

    ST Employee
    April 19, 2023

    Hello @newbie_stm32​,

    In fact, the period of the PWM signal is determined by the timer's frequency and the duration of the pulse using the HAL_TIM_PWM_ConfigChannel() function.

    You can find more details about the function attributes here.

    for example, after initializing the timer in PWM mode

    TIM_OC_InitTypeDef sConfigOC;
    sConfigOC.OCMode = TIM_OCMODE_PWM1;
    sConfigOC.Pulse = 50; // Duty cycle
    sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
    sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
    HAL_TIM_PWM_ConfigChannel(&htim, &sConfigOC, TIM_CHANNEL_1);

    you can increase the duty cycle from 50% to 75% by modifying the values of the Pulse and sConfig parameters of that function accordingly.

    Hope that helps!

    Graduate
    April 20, 2023

    Hi @Sarra.S​ it helped me a lot!!!

    Any input on changing the pulse period? As I can see it is configured in MX_TIM1_Init API for a HCLK of 170MHz for TIM1 for a 10usec period.

    htim1.Init.Prescaler = 170-1;
    htim1.Init.Period = 10;