Author Topic: Preloading a timer when doing a periodic interrupt  (Read 4701 times)

0 Members and 1 Guest are viewing this topic.

Offline peter-hTopic starter

  • Super Contributor
  • ***
  • Posts: 6149
  • Country: gb
  • Doing electronics since the 1960s...
Preloading a timer when doing a periodic interrupt
« on: November 19, 2025, 10:32:13 pm »
I've just spent a bit of time on this and found that almost nobody does preloading, so it can be quite some time (seconds) before the timer starts to generate the desired interrupt.

Look at this ST code

Code: [Select]

extern TIM_HandleTypeDef        htim6;

/**
  * @brief  This function configures the TIM6 as a time base source.
  *         The time source is configured  to have 1ms time base with a dedicated
  *         Tick interrupt priority.
  * @note   This function is called  automatically at the beginning of program after
  *         reset by HAL_Init() or at any time when clock is configured, by HAL_RCC_ClockConfig().
  * @param  TickPriority: Tick interrupt priority.
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority)
{
  RCC_ClkInitTypeDef    clkconfig;
  uint32_t              uwTimclock = 0;
  uint32_t              uwPrescalerValue = 0;
  uint32_t              pFLatency;
 
  /*Configure the TIM6 IRQ priority */
  HAL_NVIC_SetPriority(TIM6_DAC_IRQn, TickPriority ,0);
 
  /* Enable the TIM6 global Interrupt */
  HAL_NVIC_EnableIRQ(TIM6_DAC_IRQn);
 
  /* Enable TIM6 clock */
  __HAL_RCC_TIM6_CLK_ENABLE();
 
  /* Get clock configuration */
  HAL_RCC_GetClockConfig(&clkconfig, &pFLatency);
 
  /* Compute TIM6 clock */
  uwTimclock = 2*HAL_RCC_GetPCLK1Freq();
   
  /* Compute the prescaler value to have TIM6 counter clock equal to 1MHz */
  uwPrescalerValue = (uint32_t) ((uwTimclock / 1000000) - 1);
 
  /* Initialize TIM6 */
  htim6.Instance = TIM6;
 
  /* Initialize TIMx peripheral as follow:
  + Period = [(TIM6CLK/1000) - 1]. to have a (1/1000) s time base.
  + Prescaler = (uwTimclock/1000000 - 1) to have a 1MHz counter clock.
  + ClockDivision = 0
  + Counter direction = Up
  */
  htim6.Init.Period = (1000000 / 1000) - 1;
  htim6.Init.Prescaler = uwPrescalerValue;
  htim6.Init.ClockDivision = 0;
  htim6.Init.CounterMode = TIM_COUNTERMODE_UP;
  if(HAL_TIM_Base_Init(&htim6) == HAL_OK)
  {
    /* Start the TIM time Base generation in interrupt mode */
    return HAL_TIM_Base_Start_IT(&htim6);
  }
 
  /* Return function status */
  return HAL_ERROR;
}

/**
  * @brief  Starts the TIM Base generation in interrupt mode.
  * @param  htim TIM Base handle
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_TIM_Base_Start_IT(TIM_HandleTypeDef *htim)
{
  uint32_t tmpsmcr;

  /* Check the parameters */
  assert_param(IS_TIM_INSTANCE(htim->Instance));

  /* Enable the TIM Update interrupt */
  __HAL_TIM_ENABLE_IT(htim, TIM_IT_UPDATE);

  /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */
  tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS;
  if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr))
  {
    __HAL_TIM_ENABLE(htim);
  }

  /* Return function status */
  return HAL_OK;
}

Ignore the usual ST garbage. I can't see they are preloading CNT anywhere so that might have to run all the way up to 65536.

As a result, I spent a bit of time doing TIM3 to get it to work properly

[code]

// Set up TIM3 for frequency_hz.
// Timer 3 runs from APB1 (PCLK1) * 2
// This code was not trivial!
// Currently we have 1749 in ARR for 48kHz. With this we can go down to 1.3kHz before ARR overflows.

static void config_TIM3(uint32_t frequency_hz)
{

__HAL_RCC_TIM3_CLK_ENABLE(); // TIM1EN=1 in RCC2ENR and does a short delay
TIM3->CR1 = TIM_CR1_ARPE | TIM_CR1_URS; // Upcounter, auto reload, counter disabled for now (CEN=0)
    TIM3->PSC = TIM3_PRESCALER; // We assume ARR has enough range, otherwise PSC needs changing too
    TIM3->ARR = ((2*HAL_RCC_GetPCLK1Freq()) / (frequency_hz * (TIM3_PRESCALER+1)) - 1);
    TIM3->CNT = 0; // Preload counter so it starts right away
TIM3->EGR = TIM_EGR_UG; // Generate update event to load prescaler and ARR values
TIM3->CR1 &= ~TIM_CR1_DIR;  // Count up
TIM3->CR1 &= ~TIM_CR1_CMS;  // Edge-aligned mode
TIM3->DIER |= TIM_DIER_UIE;  // Update interrupt enable
TIM3->SR &= ~TIM_SR_UIF; // Clear update interrupt flag
NVIC_SetPriority(TIM3_IRQn, 0);  // NVIC: Set highest priority
NVIC_EnableIRQ(TIM3_IRQn);        // NVIC: Enable interrupt
TIM3->CR1 |= TIM_CR1_CEN;  // Counter enable

}


Am I missing something subtle? TIM3 and TIM6 are very similar; in this case identical. I am generating a 48kHz int (ARR=1749) and the TIM6 code is doing 1kHz interrupt.
Z80 Z180 Z280 Z8 S8 8031 8051 H8/300 H8/500 80x86 90S1200 32F417
 

Offline jnk0le

  • Regular Contributor
  • *
  • Posts: 230
  • Country: pl
Re: Preloading a timer when doing a periodic interrupt
« Reply #1 on: November 19, 2025, 10:45:21 pm »
Not setting TIMx->CNT to 0?

Probably relying on the reset state of peripheral registers (which is 0).
 

Offline jpanhalt

  • Super Contributor
  • ***
  • Posts: 4856
  • Country: us
Re: Preloading a timer when doing a periodic interrupt
« Reply #2 on: November 19, 2025, 10:49:19 pm »
I've just spent a bit of time on this and found that almost nobody does preloading...

I don't think I would agree with that for those who do Assembly.  As just one example, with PIC and a 16-bit timer, it's quite easy to set the high bit and get nice, 1 second interrupts.
« Last Edit: November 19, 2025, 10:51:04 pm by jpanhalt »
 

Online nctnico

  • Super Contributor
  • ***
  • Posts: 30424
  • Country: nl
    • NCT Developments
Re: Preloading a timer when doing a periodic interrupt
« Reply #3 on: November 20, 2025, 01:30:31 am »
Typically you'd keep a timer in reset (counter held at zero) while configuring it and remove the reset condition once the timer is configured properly. But this could be happening somewhere else in the HAL code. If not, then there could be a problem indeed.
« Last Edit: November 20, 2025, 01:43:39 am by nctnico »
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline peter-hTopic starter

  • Super Contributor
  • ***
  • Posts: 6149
  • Country: gb
  • Doing electronics since the 1960s...
Re: Preloading a timer when doing a periodic interrupt
« Reply #4 on: November 20, 2025, 07:18:55 am »
Not sure there is a reset to zero on this timer.

Anyway, as shown in the 2nd bit of code above, I do
TIM3->CNT = 0;
and that solved it.

I am pretty sure TIM3 is not accessed by anything else, yet after a few seconds post-power-on it contained all sorts of values.

It is supposed to be reset at power-up but clearly this doesn't always happen. In any case, if the system is stopped and restarted, there will be garbage in CNT and that is probably what was happening.
« Last Edit: November 20, 2025, 08:30:35 am by peter-h »
Z80 Z180 Z280 Z8 S8 8031 8051 H8/300 H8/500 80x86 90S1200 32F417
 

Offline ozcar

  • Frequent Contributor
  • **
  • Posts: 405
  • Country: au
Re: Preloading a timer when doing a periodic interrupt
« Reply #5 on: November 20, 2025, 10:58:00 am »
I thought that generating an update event via TIM_EGR_UG, as you do, would set the counter, either to zero if counting up, or to ARR value if counting down. At the point you generate the update event, you have already rewritten all of CR1, but I note from the fine manual that the DIR bit in CR1 is read-only in some modes, and it is a bit of a worry if the timer is in some random state before you begin. I'd be trying to find out why that is happening, or else start by setting all the timer registers to the defined reset values.
« Last Edit: November 20, 2025, 11:01:10 am by ozcar »
 

Offline peter-hTopic starter

  • Super Contributor
  • ***
  • Posts: 6149
  • Country: gb
  • Doing electronics since the 1960s...
Re: Preloading a timer when doing a periodic interrupt
« Reply #6 on: November 20, 2025, 12:04:18 pm »
I also suspect that running under a debugger and breakpoints, starting and stopping, can cause this problem, possibly (or not) related to the config under Debug whether you want timers stopped on a breakpoint.
Z80 Z180 Z280 Z8 S8 8031 8051 H8/300 H8/500 80x86 90S1200 32F417
 

Offline cv007

  • Super Contributor
  • ***
  • Posts: 1071
Re: Preloading a timer when doing a periodic interrupt
« Reply #7 on: November 20, 2025, 10:39:00 pm »
A good place for the timer to be reset is when it is enabled via rcc. I don't think there is any reason not to- if you are enabling the timer via rcc, code must be assuming it was not rcc enabled  and is not going to write to any timer register until the timer is enabled in rcc. If the timer was previously rcc enabled (and timer registers are now in an unknown state), and code (re-) enables the timer in rcc, by also first doing a timer reset in rcc that code will always get the reset state it was expecting.

An example from my stm32g071, which rcc resets/enables in the constructor, and also gives access to the rcc reset when you want to reconfigure-
Code: [Select]
                //other includes also
                #include "Tim67.hpp"
                auto tim7_callback(Tim67&){ led.toggle(); };
                auto tim7 = Tim67(MCU::TIM7)                //constructor resets/enables timer in RCC
                                .periodHz(10)               //period will be calculated from Hz (5Hz, since we toggle led)
                                .callback(tim7_callback);   //set callback for irq

                int
main            ()
                {
                uart, "tim7 Hz: ", tim7.periodHz(), endl, //hz should match what we set (now computed from registers)
                      "tim7 count: ", tim7.count(), endl; //should be 0
                tim7.irqOn(); //blink at 5Hz for 10s (all irq work is taken care of in function- cortex-m, peripheral)
                wait(10s);
                tim7.reset().periodHz(2).irqOn(); //now blink at 1Hz, reset is an rcc reset
                while(1){}
                }

The difference in creating your own code vs using the hal, is that for the hal you have to decode a bunch of macros in various files to understand what is actually happening. In general, it appears to me the typical hal code is somewhere between low level and high level- you get more than low level but they still leave enough for the user to do such as in this case where for whatever reason you are not getting registers in a reset state.

If I were to use the hal, I would put my own functions on top of it whether using LL or not. You get what you want, get an interface you like using the arguments you need, and the hal code becomes hidden in those functions and you do not have to interact with it at the app level. I do this for a few mcu's such as an efr32 (ble) where I do not have much to do so just use what they provide but wrap it inside c++ classes so when I get to the app level I'm writing in my code and not theirs.
 

Offline peter-hTopic starter

  • Super Contributor
  • ***
  • Posts: 6149
  • Country: gb
  • Doing electronics since the 1960s...
Re: Preloading a timer when doing a periodic interrupt
« Reply #8 on: November 21, 2025, 08:20:53 am »
I posted that HAL code as an example of what ST recommend, only. And they are not loading CNT.

My code is the direct loading one below that.

It raises the incidental Q of how long to wait after enabling the clock before one can load the registers. The macro they use

__HAL_RCC_TIM3_CLK_ENABLE();      // TIM1EN=1 in RCC2ENR and does a short delay

Code: [Select]
#define __HAL_RCC_TIM3_CLK_ENABLE()     do { \
                                        __IO uint32_t tmpreg = 0x00U; \
                                        SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\
                                        /* Delay after an RCC peripheral clock enabling */ \
                                        tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\
                                        UNUSED(tmpreg); \

Their "short delay" is just a peripheral register read.
Z80 Z180 Z280 Z8 S8 8031 8051 H8/300 H8/500 80x86 90S1200 32F417
 

Offline SiliconWizard

  • Super Contributor
  • ***
  • Posts: 17844
  • Country: fr
Re: Preloading a timer when doing a periodic interrupt
« Reply #9 on: November 21, 2025, 03:13:34 pm »
They talk about it here: https://sourceforge.net/p/libopencm3/mailman/message/35719252/
So, TLDR; doesn't seem to be documented for the STM32F4 other than in an errata.

This is a shortcoming (IMO) - some MCUs will just hang on a register read/write if the peripheral clock is not enabled, and conversely, if and when the access succeeds, it's guaranteed to be synchronized, which I much prefer.
 

Offline peter-hTopic starter

  • Super Contributor
  • ***
  • Posts: 6149
  • Country: gb
  • Doing electronics since the 1960s...
Re: Preloading a timer when doing a periodic interrupt
« Reply #10 on: November 21, 2025, 03:31:26 pm »
Z80 Z180 Z280 Z8 S8 8031 8051 H8/300 H8/500 80x86 90S1200 32F417
 

Offline harerod

  • Frequent Contributor
  • **
  • Posts: 553
  • Country: de
  • ee - digital & analog
    • My services:
Re: Preloading a timer when doing a periodic interrupt
« Reply #11 on: November 21, 2025, 05:24:35 pm »
They talk about it here: https://sourceforge.net/p/libopencm3/mailman/message/35719252/
So, TLDR; doesn't seem to be documented for the STM32F4 other than in an errata.
This is a shortcoming (IMO) - some MCUs will just hang on a register read/write if the peripheral clock is not enabled, and conversely, if and when the access succeeds, it's guaranteed to be synchronized, which I much prefer.
This requirement to wait a couple of peripheral cycles (not CPU cycles) after RCC enable can be a nice trap when switching from -o0 to optimzed coder. I have run into this kind of issue on several architectures. This is one of the reasons why I prefer not to switch optimization levels between development and production. I mostly stick with -og. Another example for required waits on the F4 are adjustements to the clock generation tree.
 

Offline DavidAlfa

  • Super Contributor
  • ***
  • Posts: 6939
  • Country: es
Re: Preloading a timer when doing a periodic interrupt
« Reply #12 on: November 21, 2025, 06:01:38 pm »
You don't have to reset nor reload anything.
Just set ARR reg to the value you need. When CNT reaches this value, the timer resets and generates an UPDATE IRQ.
The ISR only has to clear the UPDATE flag.

I'm pretty sure the counters clear on power-up?
« Last Edit: November 21, 2025, 06:04:38 pm by DavidAlfa »
Hantek DSO2x1x            Drive        FAQ          DON'T BUY HANTEK! (Aka HALF-MADE)
Stm32 Soldering FW      Forum      Github      Donate
 

Offline peter-hTopic starter

  • Super Contributor
  • ***
  • Posts: 6149
  • Country: gb
  • Doing electronics since the 1960s...
Re: Preloading a timer when doing a periodic interrupt
« Reply #13 on: November 21, 2025, 06:20:31 pm »
Quote
This is one of the reasons why I prefer not to switch optimization levels between development and production. I mostly stick with -og.

Exactly my view but some say if your project does not build with -O3 etc then your coding is crap :)

Quote
I'm pretty sure the counters clear on power-up?

They probably do at power-up but there are situations where things happen a bit later where you end up with nonzero values in CNT. It may be just in a debugger environment... In my case, the RTOS task starting up TIM3 does not start until several seconds after power-up / several seconds after the Cube+debugger has reset the chip. OK, one could argue that TIM3 should not start itself running (i.e. CNT remains at 0) until initialised, but what I am seeing is different.
« Last Edit: November 21, 2025, 06:47:27 pm by peter-h »
Z80 Z180 Z280 Z8 S8 8031 8051 H8/300 H8/500 80x86 90S1200 32F417
 

Offline DavidAlfa

  • Super Contributor
  • ***
  • Posts: 6939
  • Country: es
Re: Preloading a timer when doing a periodic interrupt
« Reply #14 on: November 21, 2025, 07:58:16 pm »
I've never had issues with optimizations, except when my code was trash.
C'mon Pete, RTFM, you have eyes and know English...

« Last Edit: November 21, 2025, 08:01:21 pm by DavidAlfa »
Hantek DSO2x1x            Drive        FAQ          DON'T BUY HANTEK! (Aka HALF-MADE)
Stm32 Soldering FW      Forum      Github      Donate
 

Offline cv007

  • Super Contributor
  • ***
  • Posts: 1071
Re: Preloading a timer when doing a periodic interrupt
« Reply #15 on: November 21, 2025, 08:39:12 pm »
Quote
When CNT reaches this value, the timer resets and generates an UPDATE IRQ.
The problem, it appears, is for whatever reason CNT is past the ARR value when configured, and the timer slow enough where it takes a long time to overflow and back to where CNT meets up with ARR.

As I mentioned, the rcc enable code (a macro in the hal it would appear) should also be resetting the peripheral so in all cases you get a reset peripheral when you were expecting to. If you are rcc enabling the peripheral in the code, you are also assuming the peripheral has not already been on and is in a reset state, so just make that so by also doing an rcc reset whenever code rcc enables. In this case, CNT would be 0, regardless of its previous state.

The exception would be something like the Gpio peripheral, as it is a 'shared' peripheral and although code may be rcc enabling the port on a pin by pin basis as needed (which is harmless when enabling an already enabled port), you will not want to rcc reset a Gpio port when rcc enabling an individual pin (port) as you will reset all the other pins on the same port.
 
The following users thanked this post: peter-h

Offline Doctorandus_P

  • Super Contributor
  • ***
  • Posts: 5399
  • Country: nl
Re: Preloading a timer when doing a periodic interrupt
« Reply #16 on: November 21, 2025, 10:08:32 pm »
It's all situation dependent. Some times you don't care whether the first overflow has a different time then the other overflows, while at other times it can be essential. And beginners often don't think about this at all, but once they get bitten by it, they won't forget the experience.
 

Offline peter-hTopic starter

  • Super Contributor
  • ***
  • Posts: 6149
  • Country: gb
  • Doing electronics since the 1960s...
Re: Preloading a timer when doing a periodic interrupt
« Reply #17 on: November 21, 2025, 10:58:18 pm »
You will definitely notice if the counter is a 32 bit one and your load value is say 1000 ;)
Z80 Z180 Z280 Z8 S8 8031 8051 H8/300 H8/500 80x86 90S1200 32F417
 

Offline Doctorandus_P

  • Super Contributor
  • ***
  • Posts: 5399
  • Country: nl
Re: Preloading a timer when doing a periodic interrupt
« Reply #18 on: November 22, 2025, 01:45:20 am »
Yes, but even on 32 bit uC's such as Cortex-M most timers are 16 bit, and that will overflow quite quickly on a 50+ MHz uC, unless you use very big prescaler values.
 

Offline ozcar

  • Frequent Contributor
  • **
  • Posts: 405
  • Country: au
Re: Preloading a timer when doing a periodic interrupt
« Reply #19 on: November 22, 2025, 02:55:38 am »
You will definitely notice if the counter is a 32 bit one and your load value is say 1000 ;)

The code that you posted includes this:
Code: [Select]
...
 TIM3->CNT = 0; // Preload counter so it starts right away
 TIM3->EGR = TIM_EGR_UG; // Generate update event to load prescaler and ARR values
...

And, you say that the setting of CNT to zero there is essential?

If so, what strange state was the timer in that the very next statement did not cause CNT to be updated? Can you stop it there in debugger and check all the timer registers? Or, instead of clearing CNT, set it to say 0xFACE, and see if that changes as you step past the next statement.

BTW, I was confused by your use of the word "preload", as it seems to have nothing to do with Preload as in the "P"  of ARPE (although that can also cause a one-off startup glitch in timing).
 

Offline peter-hTopic starter

  • Super Contributor
  • ***
  • Posts: 6149
  • Country: gb
  • Doing electronics since the 1960s...
Re: Preloading a timer when doing a periodic interrupt
« Reply #20 on: November 22, 2025, 10:12:27 am »
I had a quick go and CNT=0 from the start, so the debugger is resetting the CPU currently.

However there is also a "no reset" option (which I have never used AFAIK) which might expose this issue.
Z80 Z180 Z280 Z8 S8 8031 8051 H8/300 H8/500 80x86 90S1200 32F417
 

Offline temperance

  • Super Contributor
  • ***
  • Posts: 1685
  • Country: 00
Re: Preloading a timer when doing a periodic interrupt
« Reply #21 on: November 22, 2025, 11:14:54 am »
So you first state there might be a problem.

Quote
I've just spent a bit of time on this and found that almost nobody does preloading, so it can be quite some time (seconds) before the timer starts to generate the desired interrupt.


You then state:

Quote
They probably do at power-up but there are situations where things happen a bit later where you end up with nonzero values in CNT. It may be just in a debugger environment... In my case, the RTOS task starting up TIM3 does not start until several seconds after power-up / several seconds after the Cube+debugger has reset the chip. OK, one could argue that TIM3 should not start itself running (i.e. CNT remains at 0) until initialised, but what I am seeing is different.

Now after some test you state:
Quote
I had a quick go and CNT=0 from the start, so the debugger is resetting the CPU currently.

Maybe the register containing the interrupt flag is/was visible in the debug window, clearing the flag for you instead of executing the interrupt.

To reset or not to reset?
A peripheral can always become a shared peripheral, so the better option is to always reset the peripheral.
 

Offline peter-hTopic starter

  • Super Contributor
  • ***
  • Posts: 6149
  • Country: gb
  • Doing electronics since the 1960s...
Re: Preloading a timer when doing a periodic interrupt
« Reply #22 on: November 22, 2025, 11:57:22 am »
Quote
Maybe the register containing the interrupt flag is/was visible in the debug window

Not sure that would clear the pending int; the code to clear that is

 TIM3->SR &= ~TIM_SR_UIF;      // Clear interrupt flag

But that is an interesting point, if an IP bit is cleared by a register read only.
Z80 Z180 Z280 Z8 S8 8031 8051 H8/300 H8/500 80x86 90S1200 32F417
 

Offline DavidAlfa

  • Super Contributor
  • ***
  • Posts: 6939
  • Country: es
Re: Preloading a timer when doing a periodic interrupt
« Reply #23 on: November 22, 2025, 11:59:50 am »
Timer problems with debugger... probably you're not enabling the freeze bits.
Hantek DSO2x1x            Drive        FAQ          DON'T BUY HANTEK! (Aka HALF-MADE)
Stm32 Soldering FW      Forum      Github      Donate
 

Offline peter-hTopic starter

  • Super Contributor
  • ***
  • Posts: 6149
  • Country: gb
  • Doing electronics since the 1960s...
Re: Preloading a timer when doing a periodic interrupt
« Reply #24 on: November 22, 2025, 12:30:40 pm »
The only freeze option I have seen is for the watchdog

Z80 Z180 Z280 Z8 S8 8031 8051 H8/300 H8/500 80x86 90S1200 32F417
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf

 

- - -
-->