AnsweredAssumed Answered

delay func using TIM2

Question asked by Beh on Oct 12, 2013
Latest reply on Oct 12, 2013 by Clive One
I want to write function using timer 2 for have millisecond in STM32F103 I just don't know why this doesn't work!


TIMER2 config:

void config_TIM2()
{
    NVIC_InitTypeDef NVIC_InitStructure;
    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;


/* Enable the TIM2 gloabal Interrupt */
  NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = TIM_CKD_DIV1;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    /* Initialize TIM2 Interrupt */
  NVIC_Init(&NVIC_InitStructure);


  /* TIM2 clock enable */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
  /* Time base configuration */
  TIM_TimeBaseInitStructure.TIM_Period = 360 - 1;  
  TIM_TimeBaseInitStructure.TIM_Prescaler = 10 - 1; 
  TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
  TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
  /* Initialize TIM2 */
    TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStructure);
  /* TIM IT enable */
  TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
  /* TIM2 enable counter */
  TIM_Cmd(TIM2, DISABLE);
}


here I count down each milliseconds :

void TIM2_IRQHandler()
{
    TIM_ClearITPendingBit(TIM2, TIM_FLAG_Update);
    ntime--;
}


Here wait until nms milliseconds

void delay_ms(u16 nms)
{
    ntime = nms;
    TIM_Cmd(TIM2, ENABLE);
    while (ntime);
    TIM_Cmd(TIM2, DISABLE);
}

Outcomes