Hardware: STM32F103C8T6
Platform: ARM-MDK V5.11
Principle
The capture unit of the stm32f10x timer is used to measure the frequency of the input signal.
The basic principle is to calculate the frequency of the input signal by the difference of the counter reached by two captures. If the value of the counter at the first capture is Val1, the value of the second capture counter is Val2,
The clock frequency of the timer is Ftimer, then the frequency of the input signal is finput
Finput = Ftimer/(VAL2-VAL1) (Val2 > Val1)
Or
Finput = Ftimer/(Maxval-val1 + Val2) (VAL2≤VAL1)
Where Maxval is the maximum count value of the timer
Code
Take TIM2 CH4 As an example, the timer configuration code is as follows:
voidCaptureconfig (void) {tim_icinittypedef tim_icinitstructure; Tim_icinitstructure.tim_channel=Tim_channel_4; Tim_icinitstructure.tim_icpolarity=tim_icpolarity_rising; Tim_icinitstructure.tim_icselection=Tim_icselection_directti; Tim_icinitstructure.tim_icprescaler=Tim_icpsc_div1; Tim_icinitstructure.tim_icfilter = 0x0; Tim_icinit (TIM2,&tim_icinitstructure); /*TIM Enable counter*/tim_cmd (TIM2, ENABLE); /*Enable the CC4 Interrupt Request*/tim_itconfig (TIM2, TIM_IT_CC4, ENABLE);}
Configure Nvic to enable TIM2 capture interrupts:
void Bsp_intconfig (void) { nvic_inittypedef nvic_initstructure; /* */ nvic_initstructure.nvic_irqchannel = tim2_irqn; Nvic_initstructure.nvic_irqchannelpreemptionpriority 0; Nvic_initstructure.nvic_irqchannelsubpriority 1; Nvic_initstructure.nvic_irqchannelcmd = ENABLE; Nvic_init (&nvic_initstructure);}
The frequency of the input signal is calculated in the TIM2 Interrupt processing function:
voidTim2_irqhandler (void){ StaticU16 Capture, ic4readvalue1, ic4readvalue2; StaticU8 Capturenumber =0; if(Tim_getitstatus (TIM2, tim_it_cc4) = =SET) { /*Clear TIM2 Capture compare interrupt pending bit*/tim_clearitpendingbit (TIM2, TIM_IT_CC4); if(Capturenumber = =0) { /*Get the Input Capture value*/ic4readvalue1=Tim_getcapture4 (TIM2); Capturenumber=1; } Else if(Capturenumber = =1) { /*Get the Input Capture value*/ic4readvalue2=Tim_getcapture4 (TIM2); /*Capture Computation*/ if(Ic4readvalue2 >ic4readvalue1) {Capture= (Ic4readvalue2-ic4readvalue1); } Else{Capture= ((0xFFFF-ic4readvalue1) +ic4readvalue2); } /*Frequency Computation*/Freq= (U32) Systemcoreclock/Capture; Capturenumber=0; } }}
Note: Freq is a global variable.
/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxthe endxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/
[stm32f10x] using timers to measure frequency