2

I'm currently using a timer on my STM32F091VB as below

void MX_TIM3_Init(void)
{
  htim3.Instance = TIM3;
  htim3.Init.Prescaler = 400;
  htim3.Init.Period = 1000;
  HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_1);
}

...

__HAL_TIM_SET_COMPARE(&htim3, TIM_CHANNEL_1, 1000);

Is there a way to change the htim3.Init.Period on runtime?

I'm using IAR 9.20 as IDE for instance

NicoCaldo
  • 1,171
  • 13
  • 25
  • You can probably just do something like `TIM3->ARR = new_value`. – pmacfarlane Jan 25 '23 at 17:53
  • 1
    Or use the macro `__HAL_TIM_SET_AUTORELOAD(&htim3, 1234)` – Flexz Jan 25 '23 at 18:18
  • Somewhat irrelevant, but both the pre-scaler and the auto-reload values (period) count from 0 to N. So if you want to divide the input clock by 400, set the pre-scaler to 399. If you want 1000 ticks per reload, set the period to 999. – pmacfarlane Jan 25 '23 at 22:55
  • @Flexz so I can just change your `1234` with the value of the new `Period` I need? – NicoCaldo Jan 26 '23 at 07:33
  • 1
    @NicoCaldo Yes, this macro actualy writies to the ARR register, same as pmacfarlane suggested – Flexz Jan 26 '23 at 07:59

1 Answers1

2

You can change reload value while the timer is running. You can set it manually via TIM3->ARR = new_value;, where ARR stands for "auto reload register".

You should check reference manual of your MCU - Timer section - to see how many bits wide ARR is, it can be different for different timers. Also, in control register 1 (CR1) there is ARR preload buffer function. If it is enabled, it basically means "don't update ARR with newly written value until the next counter reload". So it will finish the current cycle and only after that change the ARR. If it's disabled, it can change ARR immediately whatever current value of the counter is.

Remember, that timer clock source is not the system clock, typically APBx, possibly with multiplier (2xAPBx is common in most APB clock configurations, it's messy). That is covered in RCC section of the reference manual.

Ilya
  • 992
  • 7
  • 14