I'm trying to measure the pulse width of a signal on the STM32G431RB, and I keep getting random values from the counter registers. I've checked the signal and it's fine (PWM Signal from a receiver).
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim){
if (htim -> Instance == TIM2 && htim -> Channel == HAL_TIM_ACTIVE_CHANNEL_1 && state == 0) {
IC_Val1 = TIM2 -> CNT;
__HAL_TIM_SET_CAPTUREPOLARITY(&htim2, TIM_CHANNEL_1, TIM_INPUTCHANNELPOLARITY_FALLING);
state = 1;
}
if(htim -> Instance == TIM2 && htim -> Channel == HAL_TIM_ACTIVE_CHANNEL_1 && state == 1){
IC_CH1 == TIM2 -> CNT;
if (IC_Val1 > IC_CH1){
Difference = IC_Val1 - IC_CH1;
}
else {
Difference = (0xffffffff - IC_CH1) + IC_Val1;
}
__HAL_TIM_SET_CAPTUREPOLARITY(&htim2, TIM_CHANNEL_1, TIM_INPUTCHANNELPOLARITY_RISING);
state = 0;
}
}
I have determined the capture callback interrupt routine is being called okay, but the "Difference" variable (uint32_T) keeps giving me random numbers.
Apologies for any bad formatting, its my first post lol.

Difference?, Is it declaredvolatile. An example of the output would be helpful, they may not be truly "random". Also, how are you making this observation? It is possible that the code you are using to read the result is flawed.IC_Val1 > IC_CH1, so long as all data types are unsigned and the same width as TIM2:CNT using Modulo 2^n arithmetic.