TIM2 input capture - what is wrong with my init
I have an embedded system built around a STM8S105 which, among other things, must measure the frequency of a pulsed input. The pulses are coming in on pin 29 (PD4/TIM2 CH1) anywhere from 0 to about 1200 pulses per second. What follows is my initialization of the timer and the interrupt function. I know the interrupts are happening at the input rate because I checked with an oscilloscope and a test output in the interrupt function. But when I read the counter register in the interrupt function, it is always different, almost random. It looks like the counter never resets but I don't know why. I know it is counting input pulses because when I stop the input, the interrupts stop. Please take a look at my init and interrupt functions and tell me what I am doing wrong.
Thanks My initialize function:
TIM2->CCER1 = TIM2_CCER1_CC1E;
TIM2->IER = TIM2_IER_CC1IE;
TIM2->CR1 = TIM2_CR1_CEN;
i = (u16)(CLK_GetClockFreq() / 62500);
TIM2->ARRH = (u8)((i >> 8) & 0xFF);
TIM2->ARRL = (u8)(i & 0xFF);
TIM2->EGR = TIM2_EGR_CC1G;
My interrupt function:
u16 h,l;
h = (u16)TIM2->CCR1H;
l = (u16)TIM2->CCR1L;
inPulseCount = (h <<
8
) | l;
TIM2->SR1 = TIM2_SR1_RESET_VALUE;
TIM2->SR2 = TIM2_SR2_RESET_VALUE;
#stm8 #capture #tim2