Skip to main content
Senior
Jul 24, 2024 12:57 AM UTC
Question

Change TMR1 CH1 frequency and duty cycle on the fly

Hi,

I am using a STM32L452RET6 and need to change the PWM frequency (and later the duty cycle) of Timer1 Channel 1 multiple times and on the fly. I tried using the following code but does not change the frequency:

htim1.Init.Period = 20000;
HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_1); //

 

Could someone please help with the following:

1) which registers do I need to change for frequency and which for duty cycle?

2) is that htim1.Init.Period = 20000; the correct way to change the frequency or do I need to call a dedicated function?

3) if that is the correct way, is there an additional HAL function I need to call to "load" that new value?

 

Thank you :)

This topic has been closed for replies.

7 replies

waclawek.jan
Super User
Jul 24, 2024 9:20 AM UTC

> which registers do I need to change for frequency

TIM1->ARR

But I strongly recommend to have ARR preload on (TIM1->CR1.ARPE = 1).

> and which for duty cycle?

TIM1->CCR1

I don't use Cube and can't help with that.

JW

RickoAuthor
Senior
Jul 24, 2024 4:42 PM UTC

Thank you, :)

does someone who use Cube advice on how to do it using HAL API?

 

Thank you

MKanc.1
Associate III
Jul 24, 2024 5:30 PM UTC

By re-initialization probably. HAL does not provide enough freedom to change TIMER settings. Even at some point, LL routines does not help.

Use LL whenever possible. More fun to play.

RickoAuthor
Senior
Jul 25, 2024 11:34 PM UTC

Thank you both.

Is there a way to generate a PWM that is controlled by another PWM with a 50% duty cycle?

So for example for one second it pulses at 1KHz and for the following second it is off, then start all over again. So to have regular pulse trains running automatically instead of having the software turning on and off just one PWM.

Thank you

MKanc.1
Associate III
Jul 26, 2024 12:16 AM UTC

Advanced timers have "combined channels" ability to AND or OR two PWMs which is your expectation i guess. I don't have experience but moderator can help you. You can easily change settings in pinout tab

waclawek.jan
Super User
Jul 26, 2024 6:50 AM UTC

I don't think "combined channel" is the answer here. Rather, set up two timers as master-slave; master would be slower-running i.e. have 1 second period, with PWM set on one of its channels and that channel selected as TRGO in TIMx_CR2.MMS; the other would be the slave, set up for the 1kHz PWM, with the master timer selected as TRGI source in TIMx_SMCR.TS and Gated mode selected in TIMx_SMCR.SMS.

I believe this should be clickable in CubeMX in some way.

JW