cancel
Showing results for 
Search instead for 
Did you mean: 

Input capture without HAL with nucleo STM32g474RE

Tommino
Senior

Hello,

I would like to measure the period of a square wave (around 1 kHz) with a timer in input capture configuration. I am using TIM5_CH3 on pin PA2 (nucleo G474RE).

I would like to receive a bit of help in debugging my code since i am not able to measure the period of an external waveform (also tracked on my oscilloscopes).

void TIM5_Init_ToMeasurePeriod (void){
	 
	 // Enable the GPIOA Clock
	 RCC-> AHB2ENR |= (1<<0); // Enable the GPIOA clock writing 1 in bit 0
	 // Configure the GPIO
	 GPIOA -> MODER |= (1<<5); // Port PA2 configured as alternate function
	 GPIOA -> AFR[0] |= (1<<9); // Set alternate Function 2 i.e. TIM5_CH3 for PA2 
	 // Enable the timer clock
	 RCC->APB1ENR1 |= (1<<3); // Enable the tim5 clock writing 1 in bit 3
	 // Set the timer timebase
	 TIM5 -> PSC = 1; // 80 MHz/2= 40MHz clock --> 0.025 us count set the resolution (1ms=40000 counts)
	 TIM5-> ARR = 0xFFFF; 
	 TIM5 -> CCMR2 |= (1<<0); // CC3 channel configured as input and tim_ic3 is mapped on tim_ti3
	 TIM5 -> CCMR2 |= (1<<5); // Input capture filter set to N=4. 4 consecutive samples with the new level are required (to avoid noise during the toggling)
	 TIM5-> TISEL |= (0<<16); // TIM5_ch3 is the input of the timer
	  TIM5->CCER |= (1<<8)|(0<<0)|(0<<0); // Enable capture from the counter into the capture register
	 //TIM5->DIER |= (1<<3); // interupt enable for channel 3 not used now
	 // start the timer
	 TIM5 -> CR1|= TIM_CR1_CEN;
	 /* Clear the Capture event flag for channel 1 */
	 //TIM5->SR = ~TIM_SR_CC3IF;
 
 
}
uint32_t Period;
int main(void)
{
 
TIM5_Init_ToMeasurePeriod();
 
while (!(TIM5->SR & TIM_SR_CC3IF)){}
    	 /* An active edge was detected, so store the timestamp */
    	 period = TIM5 -> CCR3; // store the CCR register in 0.025 us counts
 
 

Thanks a lot

0693W00000Nq2E1QAJ.png0693W00000Nq2EGQAZ.png

11 REPLIES 11
Tommino
Senior

Thanks @Community member​ 

It works well now.

Actually there is still a "glitch" in the period value computed which I think it happens when the register autoreloads. Do you think I can remove this effect somehow:with a different HW configuration? or should I just accept it and try to remove the sw reading?

You want to perform modulo arithmetics, taking into account C integer promotion rules.

For example, read Piranha's post in https://community.st.com/s/question/0D53W00001Z8oZqSAJ/multiple-choices-for-microsecond-delay-which-ones-better .

JW