将TIM4装备成输入捕获功用用于核算矩形波的周期。
#define NVIC_Priority_Timer4 1
void TIM4_Init_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
TIM_ICInitTypeDef TIM_ICInitStructure; //输入捕获结构体
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; //时基结构体
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD, ENABLE);
/*
*PD15-TIM4_Ch4 矩形方波的输入管脚
*/
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_15;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOD, &GPIO_InitStructure);
GPIO_PinRemapConfig(GPIO_Remap_TIM4 , ENABLE); //TIM4_CH4/PD15 硬件现已映射好的,不能将TIM4_CH4用于其他管脚
NVIC_InitStructure.NVIC_IRQChannel = TIM4_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = NVIC_Priority_Timer4;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 4;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
/*
* 设置TIM4的时基:(1+TIM_Prescaler )/72M)*(1+TIM_Period )=((1+0xFFFF)/72M)*(1+71) = 65536/1M
* (定时器计满16位用时,则计一个数用时1/1M)
*/
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
TIM_TimeBaseStructure.TIM_Prescaler = 71;
TIM_TimeBaseStructure.TIM_ClockDivision = 0x0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);
TIM_ICInitStructure.TIM_Channel = TIM_Channel_4;
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Falling; //PD15管脚检测下降沿
TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
TIM_ICInitStructure.TIM_ICFilter = 0xF;
TIM_ICInit(TIM4, &TIM_ICInitStructure);
TIM_Cmd(TIM4, ENABLE);
TIM_ITConfig(TIM4, TIM_IT_CC4, ENABLE);
}
stm32f10x_it.c文件中
unsigned int IC4ReadValue1 = 0;
unsigned int IC4ReadValue2 = 0;
unsigned int CaptureNumber_ch4 = 0;
unsigned int Capture_ch4 = 0;
void TIM4_IRQHandler(void)
{
//每逢PD15管脚检测到下降沿,就会进入到该中止处理函数
if (TIM_GetITStatus(TIM4, TIM_IT_CC4) == SET)
{
TIM_ClearITPendingBit(TIM4, TIM_IT_CC4);
if (CaptureNumber_ch4 == 0)
{
CaptureNumber_ch4 = 1;
IC4ReadValue1 = TIM_GetCapture4(TIM4);
}
else if (CaptureNumber_ch4 == 1)
{
CaptureNumber_ch4 = 0;
IC4ReadValue2 = TIM_GetCapture4(TIM4);
if (IC4ReadValue2 > IC4ReadValue1)
{
Capture_ch4 = (IC4ReadValue2 – IC4ReadValue1);
}
else if (IC4ReadValue2 < IC4ReadValue1)
{
Capture_ch4 = ((0xFFFF – IC4ReadValue1) + IC4ReadValue2);
}
else
{
Capture_ch4 = 0;
}
}
}
}