一个TIMx含有4个CCR寄存器(compare capture register),Example6中,TIM2被用于检测输入波形,使用到了2个CCR,CCR1用于记录整个周期的计数,CCR2用于记录高电平的计数。CCR1由高电平触发,而CCR2由低电平触发。
其中一个TIxFP信号被作为触发输入信号,并且从模式控制器被配置成复位模式。
int main(void)
{ /* System Clocks Configuration */
RCC_Configuration();
/* NVIC configuration */
NVIC_Configuration(); //打开TIM2的中断
/* Configure the GPIO ports */
GPIO_Configuration();
// GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
/* TIM2 configuration: PWM Input mode ------------------------
The external signal is connected to TIM2 CH2 pin (PA.01),
The Rising edge is used as active edge,
The TIM2 CCR2 is used to compute the frequency value
The TIM2 CCR1 is used to compute the duty cycle value
------------------------------------------------------------ */
TIM_ICInitStructure.TIM_ICMode = TIM_ICMode_PWMI; //2种input compare模式:PWM & input capture mode
TIM_ICInitStructure.TIM_Channel = TIM_Channel_2;
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising; //input signal active edge: rising edge
TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
//TIM Input 2, 3 or 4 are selected to be connected respectively to IC1 or IC2 or IC3 or IC4.
TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
//TIM Capture performed each time an edge is detected on the capture input.
TIM_ICInitStructure.TIM_ICFilter = 0x0; //input filter, the value can be 0~0xF, when toggle,the input signal maybe not stable, so we can ignore n cycles
TIM_ICInit(TIM2, &TIM_ICInitStructure);
/* Select the TIM2 Input Trigger: TI2FP2 */
TIM_SelectInputTrigger(TIM2, TIM_TS_TI2FP2); //Selects the TIMx Input Trigger source. TIM2 filtered timer input2
/* Select the slave Mode: Reset Mode */
TIM_SelectSlaveMode(TIM2, TIM_SlaveMode_Reset);
//Rising edge of the selected trigger signal (TRGI) reinitializes the counter and triggers an update of the registers.
/* Enable the Master/Slave Mode */
TIM_SelectMasterSlaveMode(TIM2, TIM_MasterSlaveMode_Enable);
/* TIM enable counter */
TIM_Cmd(TIM2, ENABLE);
/* Enable the CC2 Interrupt Request */
TIM_ITConfig(TIM2, TIM_IT_CC2, ENABLE); //set the Capture/Compare 2 as the interrupt source
//一个TIM有4个CC Registers
while(1);
}
中断程序:
void TIM2_IRQHandler(void)
{ // CCR1 是整个周期的计数值,CCR2是高电平的计数值
/* Clear TIM2 Capture compare interrupt pending bit */
TIM_ClearITPendingBit(TIM2, TIM_IT_CC2);
/* Get the Input Capture register CCR2 value */
IC2_Value = TIM_GetCapture2(TIM2);
if(IC2_Value != 0)
{
/* Duty cycle computation */
Duty_Cycle = (TIM_GetCapture1(TIM2) * 100) / IC2_Value; // duty cycle = CCR1/CCR2
/* Frequency computation */
Frequency = 72000000 / IC2_Value;
}
else
{
Duty_Cycle = 0;
Frequency = 0;
}
}
用户1337079 2008-8-26 16:01
用户1337079 2008-8-26 16:01