STM322F0- Can timers be used to get precise timeout functionality?
In my project, I want to implement a timeout feature. That is, the user sets the required time and then starts a process. The process then has to end after the set timeout value. Now, the problem is I am able to turn off the process after the set timeout value, but the time is not precise( verified with portable timer device). That is, if I set a timeout of 5 minutes, it sometimes reaches the set value by 4.40 mins or 5.10mins, randomly. What am I doing wrong here? How to prevent this to get close to precise time?
Details:
Device: STM32F051R8T6
Clock: 24 Mhz
Timer16 is configured to tick every 1 second(Prescaler = 24000, ARR = 999)
void Timer16_Init(void)
{
TIM_TimeBaseInitTypeDef Timer16_struct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM16,ENABLE);
Timer16_struct.TIM_Prescaler = 24000;
Timer16_struct.TIM_CounterMode = TIM_CounterMode_Up;
Timer16_struct.TIM_Period = 999;
Timer16_struct.TIM_ClockDivision = TIM_CKD_DIV1;
Timer16_struct.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM16, &Timer16_struct);
// That last function caused the UIF flag to get set. Clear it.
TIM_ClearITPendingBit(TIM16, TIM_IT_Update);
// Configure so that the interrupt flag is only set upon overflow
TIM_UpdateRequestConfig(TIM16, TIM_UpdateSource_Regular);
TIM_Cmd(TIM16, ENABLE);
}
void EnableTimer16Interrupt(void)
{
nvicStructure.NVIC_IRQChannel = TIM16_IRQn;
nvicStructure.NVIC_IRQChannelPriority = 0;
nvicStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&nvicStructure);
NVIC_SetPriority(TIM16_IRQn,0);
NVIC_EnableIRQ(TIM16_IRQn);
TIM_ITConfig(TIM16, TIM_IT_Update, ENABLE);
}