小弟在用定时器3的CH1来做输入捕获(引脚REMAP,PC6),想要测量输入方波的高电平时间。可程序能进入中断,但是读取的时间值一直为零,调试一天了,实在是晕,贴出来求大师指点!不胜感激,程序如下:
void tim3_cfg()
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); //使能TIM3时钟
GPIO_PinRemapConfig(GPIO_FullRemap_TIM3,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE); //使能GPIOC时钟
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6|GPIO_Pin_7|GPIO_Pin_8|GPIO_Pin_9; //PA0 清除之前设置
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD; //PA0 输入
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_ResetBits(GPIOC,GPIO_Pin_6|GPIO_Pin_7|GPIO_Pin_8|GPIO_Pin_9); //PA0 下拉
//初始化定时器3 TIM3
TIM_TimeBaseStructure.TIM_Period = 0xffff; //设定计数器自动重装值
TIM_TimeBaseStructure.TIM_Prescaler =72-1; //预分频器
TIM_TimeBaseStructure.TIM_ClockDivision = 0;//TIM_CKD_DIV1; //设置时钟分割:TDTS = Tck_tim
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上计数模式
TIM_TimeBaseInit(TIM3, &TIM3_TimeBaseStructure); //根据TIM_TimeBaseInitStruct中指定的参数初始化TIMx的时间基数单位
//初始化TIM3输入捕获参数
// ic1-- Rising
TIM3_ICInitStructure.TIM_Channel = TIM_Channel_1; //CC1S=01 选择输入端 IC1映射到TI1上
TIM3_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising; //上升沿捕获
TIM3_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI; //映射到TI1上
TIM3_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1; //配置输入分频,不分频
TIM3_ICInitStructure.TIM_ICFilter = 0x00;//IC1F=0000 配置输入滤波器 不滤波
TIM_ICInit(TIM3, &TIM3_ICInitStructure);
// TIM_TIxExternalClockConfig(TIM3, TIM_TS_ITR1, TIM_ICPolarity_Rising, 0);// TI1FP1
// TIM_SelectInputTrigger(TIM3, TIM_TS_TI1FP1);//ITR1
// TIM_SelectSlaveMode(TIM3, TIM_SlaveMode_Reset);//TIM从模式:触发信号的上升沿重新初始化计数器和触发寄存器的更新事件
// TIM_SelectMasterSlaveMode(TIM3, TIM_MasterSlaveMode_Enable); //启动定时器的被动触发
//开启TIM3的中断
TIM_ClearFlag(TIM3, TIM_IT_CC1);
TIM_Cmd(TIM3,ENABLE ); //使能定时器3
TIM_ITConfig(TIM3,TIM_IT_CC1,ENABLE);//允许更新中断 ,允许CC1IE捕获中断 TIM_IT_Update选用一种即可,不能两种同时使用,事实证明不行
}
中断设置
//中断分组初始化
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn; //TIM3中断
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //先占优先级2级
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //从优先级0级
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道被使能
NVIC_Init(&NVIC_InitStructure); //根据NVIC_InitStruct中指定的参数初始化外设NVIC寄存器
中断函数
void TIM3_IRQHandler(void)
{
if(TIM_GetITStatus(TIM3, TIM_IT_CC1) == SET)
{
//每次进入中断就改变捕获触发方式,且翻转PD2的电平
if(flag==0)
{
flag=1;
TIM3CH1_CAPTURE_VAL=TIM_GetCapture1(TIM3);//TIM3->CCR1;
ICAPvalue[0]=TIM3CH1_CAPTURE_VAL;
TIM_OC1PolarityConfig(TIM3,TIM_ICPolarity_Falling);
}
else
{
flag=0;
TIM3CH1_CAPTURE_VAL=TIM_GetCapture1(TIM3); //TIM3->CCR1;
ICAPvalue[1]=TIM3CH1_CAPTURE_VAL;
TIM_OC1PolarityConfig(TIM3,TIM_ICPolarity_Rising);
ICAPvalue[3]=ICAPvalue[1]-ICAPvalue[0];
}
}
TIM_ClearITPendingBit(TIM3, TIM_IT_CC1);
} |