Strange values from HAL_TIM_ReadCapturedValue
I'm using input capture with a 16 bit timer to read a 1.5ms pulse that occurs every 20ms. I can see on my scope that the input pulse conforms to this exactly. Here's the code for the interrupt callback:
uint16_t pwmVal0 = 0;
uint16_t pwmVal1 = 0;
uint16_t pwmLength = 0;
uint8_t whichEdge = 0;
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
if ( htim == &htim3 && htim->Channel == HAL_TIM_ACTIVE_CHANNEL_1 ) {
if ( whichEdge == 0 ) {
//HAL_GPIO_WritePin(GPIOD, GPIO_PIN_2, GPIO_PIN_SET);
pwmVal0 = HAL_TIM_ReadCapturedValue( htim, TIM_CHANNEL_1 );
__HAL_TIM_SET_CAPTUREPOLARITY( htim, TIM_CHANNEL_1, TIM_INPUTCHANNELPOLARITY_FALLING );
whichEdge = 1;
}
else {
//HAL_GPIO_WritePin(GPIOD, GPIO_PIN_2, GPIO_PIN_RESET);
pwmVal1 = HAL_TIM_ReadCapturedValue( htim, TIM_CHANNEL_1 );
__HAL_TIM_SET_CAPTUREPOLARITY( htim, TIM_CHANNEL_1, TIM_INPUTCHANNELPOLARITY_RISING );
whichEdge = 0;
pwmLength = pwmVal1 - pwmVal0;
}
}
}Note the two commented lines. When I look at the pulses made by those on my scope, the detected waveform is exactly what I expect and is rock solid. So the interrupt is triggering just fine. The problem is that the values returned by HAL_TIM_ReadCapturedValue (and used to calculate my final goal value 'pwmLength') are only correct about 70% of the time. Here's the result:

Every value in this array should be around 1500, but there are consistently values around 62941 showing up, with a regular repetition.
What's weird is I've used this method many times in the past with no such problems. Is it possible that the hardware is at fault maybe?
