cancel
Showing results for 
Search instead for 
Did you mean: 

How to know when HAL_TIM_IC_CaptureCallback function is done

ELith
Associate

i have code in HAL_TIM_IC_CaptureCallback

void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim) {
 
if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_1) {
	/* Get the Input Capture value */
	iC2Value1 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_1);
 
	if (iC2Value1 != 0) {
		/* Duty cycle computation */
		iC2Value2 = ((HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_2)));
		distance = ((float) iC2Value2) / 147.0;
		dutyCycle = (iC2Value2 * 100.0) / (float) iC2Value1;
 
		/* uwFrequency computation
		 TIM4 counter clock = (RCC_Clocks.HCLK_Frequency) */
		frequency = (float) HAL_RCC_GetHCLKFreq() / (float) iC2Value1;
		
	} else {
		dutyCycle = 0;
		frequency = 0;
	}
}
}

i want to set a flag in there to know when the capture has finished ie when done flag=1 so that i can proceed with doing something else in my while loop. Although what i found is that that the

void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim) {
 
 
 
if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_1) {
 

runs multiple times for when getting one capture( i may be wrong on this i'm not sure but that seemed to be the case). Can someone let me know how to set a flag so i know when the capture has finished

3 REPLIES 3
S.Ma
Principal

With HAL, create a global

uint8_t flag = 0;

uint32_t result;

Set it in the callback once the job is done and use it there to skip unused interrupts coming after this to preserve the "result"

Once the main loop has used the data, it will clear the flag to let the interrupt continue.

Without the HAL and using LL, the ISR could simply turn itself off once the job is done and it will be the main loop to reenable the interrupt for the next "sampling measurement".

Bob S
Principal

If you are going to try @S.Ma​  suggestion, please declare the "flag" variable as "volatile uint8_t flag".

Meanwhile, when you appear to get multiple calls to the capture callback, are they all for your active channel? Or do you have multiple input capture channels active?

Is the input signal noisy or does it bounce on rising or falling edges thus generating multiple capture events?

MPlan.7
Associate III

The examples I found did not check channel - after all, if each of your timers is using the same channel this will succeed every time. Instead they check instance.

Try (htim->Instance == TIM3) instead.

If (htim->Instance == TIM3)
{
  // do stuff for this timer here
}

The HAL actually contains the ability to set up separate callback functions for each timer instance, but it is disabled by default. I found this very strange behavior; worse, far too many of the examples fail to properly wrap their specific timer code as above (because they're only using one timer). I hope this helps.