大学生
最后登录1970-1-1
在线时间 小时
注册时间2013-5-27
|
楼主 |
发表于 2013-10-14 16:08:45
|
显示全部楼层
#include "timer.h"
#include "usart.h"
//定时器5通道1输入捕获配置
TIM_ICInitTypeDef TIM5_ICInitStructure;
void TIM5_Cap_Init(u16 arr,u16 psc)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5, ENABLE); //使能TIM5时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); //使能GPIOA时钟
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2|GPIO_Pin_3; //PA0 清除之前设置
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD; //PA0 输入
GPIO_Init(GPIOA, &GPIO_InitStructure);
//初始化定时器5 TIM5
TIM_TimeBaseStructure.TIM_Period = arr; //设定计数器自动重装值
TIM_TimeBaseStructure.TIM_Prescaler =psc; //预分频器
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //设置时钟分割:TDTS = Tck_tim
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上计数模式
TIM_TimeBaseInit(TIM5, &TIM_TimeBaseStructure); //根据TIM_TimeBaseInitStruct中指定的参数初始化TIMx的时间基数单位
//初始化TIM5输入捕获参数
TIM5_ICInitStructure.TIM_Channel = TIM_Channel_3; //CC1S=01 选择输入端 IC1映射到TI1上
TIM5_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising; //上升沿捕获
TIM5_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI; //映射到TI1上
TIM5_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1; //配置输入分频,不分频
TIM5_ICInitStructure.TIM_ICFilter = 0x00;//IC1F=0000 配置输入滤波器 不滤波
TIM_ICInit(TIM5, &TIM5_ICInitStructure);
//中断分组初始化
NVIC_InitStructure.NVIC_IRQChannel = TIM5_IRQn; //TIM3中断
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2; //先占优先级2级
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //从优先级0级
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道被使能
NVIC_Init(&NVIC_InitStructure); //根据NVIC_InitStruct中指定的参数初始化外设NVIC寄存器
TIM_ITConfig(TIM5,TIM_IT_CC3,ENABLE);//允许更新中断 ,允许CC1IE捕获中断
TIM_Cmd(TIM5,ENABLE ); //使能定时器5
}
u8 TIM5CH_CAPTURE_STA[2]={0,0}; //输入捕获状态
u16 TIM5CH_CAPTURE_VAL[2]={0,0};//输入捕获值2
u16 TIM5CH_CAPTURE_VAL2[2]={0,0}; //输入捕获值
//定时器5中断服务程序
void TIM5_IRQHandler(void)
{
if (TIM_GetITStatus(TIM5, TIM_IT_CC3) != RESET)//捕获1发生捕获事件
{
if(TIM5CH_CAPTURE_STA[0]==1) //捕获到一个下降沿
{
TIM5CH_CAPTURE_STA[0]=0;
TIM5CH_CAPTURE_VAL2[0]=TIM_GetCapture3(TIM5);
TIM_OC3PolarityConfig(TIM5,TIM_ICPolarity_Rising); //CC1P=0 设置为上升沿捕获
if(TIM5CH_CAPTURE_VAL2[0]>=TIM5CH_CAPTURE_VAL[0])
printf("TIM5CH_CAPTURE_VAL:%d us\r\n",TIM5CH_CAPTURE_VAL2[0]-TIM5CH_CAPTURE_VAL[0]);//打印总的高点平时
else
printf("TIM5CH_CAPTURE_VAL:%d us\r\n",0xffff+TIM5CH_CAPTURE_VAL2[0]-TIM5CH_CAPTURE_VAL[0]);//打印总的高点平时
}
else //还未开始,第一次捕获上升沿
{
TIM5CH_CAPTURE_STA[0]=1; //标记捕获到了上升沿
TIM5CH_CAPTURE_VAL[0]=TIM_GetCapture3(TIM5);
TIM_OC3PolarityConfig(TIM5,TIM_ICPolarity_Falling); //CC1P=1 设置为下降沿捕获
}
}
TIM_ClearITPendingBit(TIM5, TIM_IT_CC3); //清除中断标志位
}
|
|