cancel
Showing results for 
Search instead for 
Did you mean: 

Change TIM2 prescalar value on the go

tybandara
Associate II
Posted on December 11, 2012 at 13:05

Hello all experts,

I have configured the TIM2 timer of my stm32f4 discovery board. Now I want to change the prescalar value of it on the go. My code is as follows

**************************************************

void TIM2_IRQHandler(void)

{

  if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)

  {

    TIM_ClearITPendingBit(TIM2, TIM_IT_Update);

        GPIO_ToggleBits(GPIOA, GPIO_Pin_5);

   }

}

*************************************************

void INTTIM_Config(uint16_t numOfMilleseconds)

{

  NVIC_InitTypeDef NVIC_InitStructure;

  /* Enable the TIM2 gloabal Interrupt */

  NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;

  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;

  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;

  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;

  NVIC_Init(&NVIC_InitStructure);

  /* TIM2 clock enable */

  RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);

  /* Time base configuration */

  TIM_TimeBaseStructure.TIM_Period = (500*numOfMilleseconds) - 1;  // 1 MHz down to 1 KHz (1 ms)

  //TIM_TimeBaseStructure.TIM_Prescaler = 84 - 1; // 24 MHz Clock down to 1 MHz (adjust per your clock)

    TIM_TimeBaseStructure.TIM_Prescaler = 168-1; //168MHz Clock should be down to 1MHz

  TIM_TimeBaseStructure.TIM_ClockDivision = 0;

  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

    TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;

  TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);

            

  /* TIM IT enable */

    TIM_ClearITPendingBit(TIM2, TIM_IT_Update);

  TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);

  /* TIM2 enable counter */

  TIM_Cmd(TIM2, ENABLE);

}

***********************************************

int main(void)

{

    GPIO_config();

    INTTIM_Config(50);

  while (1)

  {  

  }

}

****************************************************

Initially I configure the timer to give an interrupt in 50ms duration and it succeeds. Now I want to change the interrupt duration to 100ms when I receive my first interrupt. I tried to adding this to the irq

TIM_TimeBaseStructure.TIM_Period = (500*40) - 1;  // 1 MHz down to 1 KHz (1 ms)

 TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);

But I couldn't get the required output.

Please advice me on how to achieve this task. I know this can be done since the datasheet states the preamble can be changed on the go.

Thank you for your valuable time.

Thilina

#dividers-and-prescaler-division
1 REPLY 1
Posted on December 11, 2012 at 13:36

For the PERIOD

TIM2->ARR = NewPeriod; // n-1

For the PRESCALER

TIM2->PSC = NewPrescaler; // n-1

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