Skip to main content
Graduate II
July 24, 2024
Question

Change TMR1 CH1 frequency and duty cycle on the fly

  • July 24, 2024
  • 4 replies
  • 1593 views

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.

    4 replies

    Super User
    July 24, 2024

    > 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
    Graduate II
    July 24, 2024

    Thank you, :)

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

     

    Thank you

    Graduate
    July 24, 2024

    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
    Graduate II
    July 25, 2024

    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

    Graduate
    July 26, 2024

    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

    Super User
    July 26, 2024

    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