TIM3 CH2 PB5一但为低电平,内部TIM3开始计数
void TIM3_Counter_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_PinRemapConfig(GPIO_PartialRemap_TIM3, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
TIM_SelectInputTrigger(TIM3, TIM_TS_TI2FP2);
TIM_SelectSlaveMode(TIM3, TIM_SlaveMode_Gated);
TIM3_ICInitStructure.TIM_Channel = TIM_Channel_2;
TIM3_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Falling;
TIM3_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
TIM3_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
TIM3_ICInitStructure.TIM_ICFilter = 4;
TIM_ICInit(TIM3, &TIM3_ICInitStructure);
TIM_TimeBaseStructure.TIM_Period = 65535;
TIM_TimeBaseStructure.TIM_Prescaler =0;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
TIM_SetCounter (TIM3, 0);
TIM_Cmd(TIM3, ENABLE);
}
开始计数前设置:
TIM_SetCounter (TIM3, 0);
计数完成后,获取脉冲宽度:
int PluseWidth=TIM_GetCounter(TIM3);