Skip to main content
Senior III
August 3, 2018
Question

Basic question regarding timers and generating a simple delay

  • August 3, 2018
  • 2 replies
  • 735 views

Hi there,

Let say I want to generate a 1 ms delay using a timer. I set my prescaler to have a 1ms granularity

TIMx->PSC = (uint16_t)((SystemCoreClock / 1000U) - 1);

Now if I want to generate a 2ms delay I usually do it like this (assuming the UIF flag is already cleared and that the timer is not running).

TIMx->ARR = 2 - 1;
TIMx->CR1 = TIM_CR1_CEN; // Enable the TIM Counter
while((TIMx->SR & TIM_SR_UIF) == 0) ; // Wait for Timer overflow

Everything works as it should for any delay except if I want to generate a 1ms delay. Using the same method I have to change the prescaler to something.

My question is : is there a way to generate a 1ms delay with a 1ms prescaler ?

    This topic has been closed for replies.

    2 replies

    waclawek.jan
    Super User
    August 3, 2018

    There may be several many ways to achieve this, depending on what you exactly want, e.g.

    tmp = TIMx->CNT;

    while (TIMx->CNT == tmp);

    How well this will function will of course depend on the circumstances - if the timer is already running, this may result in shorter than expected delay. Forcing an update event through setting EGR.UG before this sequence may reset the prescaler counter resulting in the expected delay, but that also has other effects, which may or may not matter for your particular purpose.

    Btw., if run after reset (i.e. after a timer reset, which resets PSC to 0), your code won'r result in 1ms delay, rather, 1ms + 2 timer clock cycles, as it takes an update event the real prescaler counter to be loaded from the PSC register.

    Tesla DeLorean
    Guru
    August 3, 2018

    The Prescaler should be the smaller of the two factors

    Update occurs when at count zero

    For 1ms clock at 1 MHz and observe 1000 ticks of a free running counter ​

    Tips, Buy me a coffee, or three.. PayPal VenmoUp vote any posts that you find helpful, it shows what's working..