这是上周我学输入捕获的时候写的源代码,超声波测距,通过串口显示。- void TIM3_CAP_Init(u16 arr,u16 psc)
- {
-
- GPIO_InitTypeDef GPIO_InitStructure;
- TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
- TIM_ICInitTypeDef TIM_ICInitStructure;
- NVIC_InitTypeDef NVIC_InitStructure;
-
- //使能相应时钟
- RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
-
- //GPIOA 0 初始化
- GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD; //输入下拉
- GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
- GPIO_Init(GPIOA,&GPIO_InitStructure);
- GPIO_ResetBits(GPIOA,GPIO_Pin_0); //设置为低电平
-
- //初始化定时器
- TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1; //不分频
- TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; //向上计数
- TIM_TimeBaseInitStructure.TIM_Period = arr; //自动重装载的值
- TIM_TimeBaseInitStructure.TIM_Prescaler = psc; //预分频的系数
- TIM_TimeBaseInit(TIM3,&TIM_TimeBaseInitStructure);
-
- //初始化捕获通道
- TIM_ICInitStructure.TIM_Channel = TIM_Channel_1; //通道1
- TIM_ICInitStructure.TIM_ICFilter = 0x00; //不使用虑波器
- 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);
-
- //初始化中断
- NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn; //TIM3中断
- NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
- NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
- NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
- NVIC_Init(&NVIC_InitStructure);
-
-
- //开启捕获和更新中断
- TIM_ITConfig(TIM3,TIM_IT_Update | TIM_IT_CC1, ENABLE);
-
- //使能定时器
- TIM_Cmd(TIM3,ENABLE);
-
-
- }
- u8 TIM3CH1_CAPTURE_STA = 0;
- u16 TIM3CH1_CAPTURE_VAL = 0;
- //中断服务函数
- void TIM3_IRQHandler(void)
- {
- if((TIM3CH1_CAPTURE_STA & 0x80) == 0) //如果还没完成捕获
- {
- if(TIM_GetITStatus(TIM3,TIM_IT_Update) != RESET) //更新中断来了
- {
- if(TIM3CH1_CAPTURE_STA & 0x40) //如果上一次捕获到高电平
- {
- if((TIM3CH1_CAPTURE_STA & 0x3f) == 0x3f) //如果定时器溢出次数记满了
- {
- TIM3CH1_CAPTURE_STA |= 0x80; //记满了强制捕获完成
- TIM3CH1_CAPTURE_VAL = 0xffff; //记满
- }
- else //否则
- {
- TIM3CH1_CAPTURE_STA ++; //每来一次更新中断自加一次
- }
- }
- }
- if(TIM_GetITStatus(TIM3,TIM_IT_CC1) != RESET) //如果捕获中断来了
- {
- if(TIM3CH1_CAPTURE_STA & 0x40) //如果上次捕获到高电平
- {
- TIM3CH1_CAPTURE_STA |= 0x80; //捕获完成
- TIM3CH1_CAPTURE_VAL = TIM_GetCapture1(TIM3); //将通道的值给 VAL
- TIM_OC1PolarityConfig(TIM3,TIM_ICPolarity_Rising); //完成捕获还要设置下降沿触发
- }
- else //第一次捕获
- {
- TIM3CH1_CAPTURE_STA = 0; //清零
- TIM3CH1_CAPTURE_VAL = 0;
- TIM_SetCounter(TIM3,0);
- TIM3CH1_CAPTURE_STA |= 0x40; //采集到高电平了
- TIM_OC1PolarityConfig(TIM3,TIM_ICPolarity_Falling); //设置下降沿触发
- }
- }
- }
- TIM_ClearITPendingBit(TIM3,TIM_IT_Update | TIM_IT_CC1); //清除中断标志位
- }
复制代码 全部资料51hei下载地址:
8.3 输入捕获(超声波测距).7z
(183.95 KB, 下载次数: 55)
|