cancel
Showing results for 
Search instead for 
Did you mean: 

STM32G4 PWM. Changing period and duty cycle.

newbie_stm32
Associate III

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?

4 REPLIES 4
gbm
Lead III

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;

My STM32 stuff on github - compact USB device stack and more: https://github.com/gbm-ii/gbmUSBdevice
newbie_stm32
Associate III

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.

Sarra.S
ST Employee

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!

To give better visibility on the answered topics, please click on Accept as Solution on the reply which solved your issue or answered your question.

newbie_stm32
Associate III

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;