32位单片机

服务热线:13828722724

中科芯32位MCU CKS32F103C8T6进行输入捕获的方法

2020-04-24 11:54:11   责任编辑:     0

  中科芯提供各种基于Cortex-M内核的MCU,广泛应用于物联网、智能家居、可穿戴设备等领域,这其中很多地方都要涉及到输入捕获。输入捕获可以用来测量脉冲宽度或者测量频率。输入捕获要用到普通定时器,CKS32F103C8T6包含3个普通定时器(TIM2、TIM3、TIM4)和1个高级控制定时器(TIM1),下面我们用普通定时器TIM2的通道1(PA15)来实现一个输入捕获功能,捕获PA15上的高电平脉宽。

  与输入捕获有关的寄存器包括TIM2_ARR(设自动重装载值)、TIM2_PSC(时钟分频)、TIM2_CCMR1(捕获模式)、TIM2_CCER(捕获使能)、TIM2_DIER(中断使能)、TIM2_CR1(使能定时器)、TIM2_CCR1(存储TIM2_CNT捕获的值)。


  配置步骤如下:


  一、TIM2的CH1输入捕获函数

  GPIO_InitTypeDef GPIO_InitStructure;

  TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;

  NVIC_InitTypeDef NVIC_InitStructure;


  1.使能TIM2和GPIOA的时钟,配置PA15为下拉输入

  RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);

  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_15;

  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD;

  GPIO_Init(GPIOA, &GPIO_InitStructure);

  GPIO_ResetBits(GPIOA,GPIO_Pin_15);


  2.初始化TIM2,设置TIM2的ARR和PSC

  TIM_TimeBaseStructure.TIM_Period = arr;

  TIM_TimeBaseStructure.TIM_Prescaler =psc;

  TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;

  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);


  3.设置TIM2的输入比较参数,开启输入捕获

  TIM2_ICInitStructure.TIM_Channel = TIM_Channel_1;

  TIM2_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;

  TIM2_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;

  TIM2_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;

  TIM2_ICInitStructure.TIM_ICFilter = 0x00;

  TIM_ICInit(TIM2, &TIM2_ICInitStructure);


  4.使能中断,初始化中断优先级分组,使能定时器

  NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;

  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;

  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;

  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;

  NVIC_Init(&NVIC_InitStructure);

  TIM_ITConfig(TIM2,TIM_IT_Update|TIM_IT_CC1,ENABLE);

  TIM_Cmd(TIM2,ENABLE );


  二、TIM2的中断服务函数

  u8 TIM2CH1_CAPTURE_STA=0;

  u16 TIM2CH1_CAPTURE_VAL;

  void TIM2_IRQHandler(void)

  {

  if((TIM2CH1_CAPTURE_STA&0X80)==0)

  {

  if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)

  {

  if(TIM2CH1_CAPTURE_STA&0X40)

  {

  if((TIM2CH1_CAPTURE_STA&0X3F)==0X3F)

  {

  TIM2CH1_CAPTURE_STA|=0X80;

  TIM2CH1_CAPTURE_VAL=0XFFFF;

  }else TIM2CH1_CAPTURE_STA++;

  }

  }

  if (TIM_GetITStatus(TIM2, TIM_IT_CC1) != RESET)

  {

  if(TIM2CH1_CAPTURE_STA&0X40)

  {

  TIM2CH1_CAPTURE_STA|=0X80;

  TIM2CH1_CAPTURE_VAL=TIM_GetCapture1(TIM2);

  TIM_OC1PolarityConfig(TIM2,TIM_ICPolarity_Rising);

  }

  else

  {

  TIM2CH1_CAPTURE_STA=0;

  TIM2CH1_CAPTURE_VAL=0;

  TIM_SetCounter(TIM2,0);

  TIM2CH1_CAPTURE_STA|=0X40;

  TIM_OC1PolarityConfig(TIM2,TIM_ICPolarity_Falling);

  }

  }

  }

  TIM_ClearITPendingBit(TIM2, TIM_IT_CC1|TIM_IT_Update);

  }

  这样,我们的函数配置就完成了,现在定时2的通道1就可以开始输入捕获了。我们在主函数中调用此函数,就可以在PA15脚捕获高电平脉宽。

本方来源于世强元件


电话

0755-27883824

地址:深圳市宝安区西乡街道银田创意园B8栋502

传真:0755-61204158

邮箱 : 13510937553@163.com