IC(Input Capture)输入捕获
输入捕获模式下,当通道输入引脚出现指定电平跳变时,当前CNT的值将被锁存到CCR中
我们使用测周法测频率
void IC_Init(void)
{RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);GPIO_InitTypeDef GPIO_InitStruture;GPIO_InitStruture.GPIO_Mode = GPIO_Mode_IPU;GPIO_InitStruture.GPIO_Pin = GPIO_Pin_6;GPIO_InitStruture.GPIO_Speed = GPIO_Speed_50MHz;GPIO_Init(GPIOA,&GPIO_InitStruture);TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;TIM_TimeBaseInitStruct.TIM_Period = 65536 - 1; //ARRTIM_TimeBaseInitStruct.TIM_Prescaler = 72 - 1; //PSCTIM_TimeBaseInitStruct.TIM_RepetitionCounter = 0;TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStruct);TIM_ICInitTypeDef TIM_ICInitStructure;TIM_ICInitStructure.TIM_Channel = TIM_Channel_1;TIM_ICInitStructure.TIM_ICFilter = 0xF;TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;TIM_ICInit(TIM3, &TIM_ICInitStructure);TIM_PWMIConfig(TIM3, &TIM_ICInitStructure);TIM_SelectInputTrigger(TIM3, TIM_TS_TI1FP1);TIM_SelectSlaveMode(TIM3, TIM_SlaveMode_Reset);TIM_Cmd(TIM3, ENABLE);
}uint16_t IC_GetFreq(void)
{return 1000000/(TIM_GetCapture1(TIM3) + 1);
}uint16_t IC_GetDuty(void)
{return (TIM_GetCapture2(TIM3) + 1)*100/(TIM_GetCapture1(TIM3) + 1);
}
时基单元
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;TIM_TimeBaseInitStruct.TIM_Period = 65536 - 1; //ARRTIM_TimeBaseInitStruct.TIM_Prescaler = 72 - 1; //PSCTIM_TimeBaseInitStruct.TIM_RepetitionCounter = 0;TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStruct);
PSC设置为72 - 1是为了方便计算标准频率fc,为72000000/72=1000000
输入捕获
TIM_ICInitTypeDef TIM_ICInitStructure;TIM_ICInitStructure.TIM_Channel = TIM_Channel_1;TIM_ICInitStructure.TIM_ICFilter = 0xF;TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;TIM_ICInit(TIM3, &TIM_ICInitStructure);
PWMI模式
TIM_PWMIConfig(TIM3, &TIM_ICInitStructure);
与上面的全部相反,即选择通道2,下降沿触发,交叉
触发源选择
TIM_SelectInputTrigger(TIM3, TIM_TS_TI1FP1);
从模式
TIM_SelectSlaveMode(TIM3, TIM_SlaveMode_Reset);
启动定时器
TIM_Cmd(TIM3, ENABLE);
计算频率和占空比
uint16_t IC_GetFreq(void)
{return 1000000/(TIM_GetCapture1(TIM3) + 1);
}uint16_t IC_GetDuty(void)
{return (TIM_GetCapture2(TIM3) + 1)*100/(TIM_GetCapture1(TIM3) + 1);
}