AnsweredAssumed Answered

Use of clock dividers in timers (STM32F103)

Question asked by psykhi on Oct 25, 2014
Latest reply on Oct 29, 2014 by psykhi
Hi,

I have just begun toying around with a STM32F103 (on a STM32 Nucleo board) and I have some troubles understanding the expected behavior of the clock divider in the timers.

So my original goal was to simply implement a delay(uint i_ms) function that would wait a given amount of time . My implementation is the following :

My init code is the following :
/**
 * @brief Here we will initializes a general purpose timer (TIM2)
 * that will be used for the delay functions.
 */
static void init_delay_timer(void)
{
    uint16_t prescaler = 0;
    TIM_TimeBaseInitTypeDef TIM2_config;
    /*We enable RCC on the timer 2. */
    /* Timers are low speed peripherals so we use the APB1 */
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
 
    /* Now we need a prescaler value in order to achieve the clock rate we need.
     * Here we need a 1000Hz frequency*/
    prescaler = (uint16_t) ((SystemCoreClock) / 1000) - 1;
    /* Time base configuration */
    /*65535 is actually the maximum value for the counter before it wraps around */
    TIM2_config.TIM_Period = 65535;
    TIM2_config.TIM_Prescaler = prescaler;
    TIM2_config.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM2_config.TIM_CounterMode = TIM_CounterMode_Up;
 
    /* Now we call the init function */
    TIM_TimeBaseInit(TIM2, &TIM2_config);
    /* We actually start the counter */
    TIM_Cmd(TIM2, ENABLE);
}


And the delay function is :
01./**
02. * @brief wait for i_ms
03. * @param i_ms milliseconds to wait (max : 65535)
04. */
05.static void delay_ms(uint16_t i_ms)
06.{
07.    assert_param(i_ms < 65536);
08.    /* We set the counter value to 0 */
09.    TIM2->CNT = 0;
10. 
11.    /* Now we wait until we have counted enough ms*/
12.    while(TIM2->CNT < i_ms);
13.}


Which works fine. However, if I try changing the timer's clock divider from TIM_CKD_DIV1 to TIM_CKD_DIV2 (or 4), it doesn't seem to have any effect. My understanding is that my delay should then be 2, or 4 times as long as with no divider.

Am I missing something here?

Thanks!


Outcomes