Input Capture callback function inaccurate and slow?
Hi everyone,
I'm using an STM32F0 Nucleo board.
I've been trying to implement an input capture function that tries to measure the frequency of an input PWM signal. I basically record a timer count when I get the first rising edge and the second rising edge and find the difference.
However, I'm getting super inaccurate readings. For example, when I set the PWM signal to 100Hz, my frequency says 200Hz. It continues to say 200Hz even if I set my PWM to 1000Hz.
Then, if I go to 10KHz for the PWM signal, I get no readings at all. Is there something wrong with my unit?
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef * htim){
// checking if active channel is correct
if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_1){
// first need to check if first rise is captured
if (firstRise == 0){
// capture first value
captures[0] = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_1);
firstRise = 1;
}
// need the next rise
else if (firstRise == 1){
captures[1] = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_1);
if (captures[1] > captures[0]){
period = captures[1] - captures[0];
}
else{
period = 0xffff - captures[0] + captures[1] + 1;
}
// so the frequency is going to be TIM clock / period
// in this case the clock is the same as PCLK1 so...
frequency = HAL_RCC_GetPCLK1Freq()/period;
firstRise = 0; // reset the capture values
numCaptures++;
}
}
HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin);
}