stm32pwm的输入捕获

pwm的生成:

  • CubeMax的配置:
    定时器:TIM1
    时钟:内部时钟源(TIM1用的是APB2 Timerclocks配置为72MHz)
    引脚:PA6
    定时器配置:Prescaler=72-1,Period =1000-1,Pulse=500
    (pwm的频率frequency=72MHz/(Prescaler*Period))
    占空比位:Pules/(Period+1)
    计数模式(Counter Mode):up(向上计数)
    在这里插入图片描述
    pwm的捕获

  • CubeMax的配置:
    定时器:TIM3
    时钟:TIM3使用APB1Timerclocks配置为72Mhz
    引脚:PA8
    定时器配置:Prescaler = 72-1,Period = 0xffff-1
    (能捕获的最小pwm频率=72MH/Prescaler/Period)
    上升沿捕获
    开启中断
    在这里插入图片描述
    中断服务函数

  • 每检测到一次高电平产生一次中断,进入中断服务函数,第一次检测到高电平,获取定时器计数的值value1,第二次检测到高电平,获取计数的值value3。
    捕获到的pwm频率计算:frequency=(72MHz/72)/(value3-value1)

void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim) //input capture callback
{
	if(htim->Channel ==HAL_TIM_ACTIVE_CHANNEL_1)
	{
		//first we need to check for either the first value is captured or not
		if (Is_First_Captured ==0)
		{
			printf("Is_First_Captured :%d \n",Is_First_Captured);
			IC_Value1=HAL_TIM_ReadCapturedValue(htim,TIM_CHANNEL_1);
			Is_First_Captured =1;
			printf("IC_Value1:%d \n",IC_Value1);
		}
		else if(Is_First_Captured ==1)
		{
			printf("Is_First_Captured :%d \n",Is_First_Captured);
			IC_Value2=HAL_TIM_ReadCapturedValue(htim,TIM_CHANNEL_1);
			printf("IC_Value2 :%d \n",IC_Value2);
			if(IC_Value2 >IC_Value1)
			{
				Difference =IC_Value2-IC_Value1;
				printf("difference:%d \n" ,Difference);
			}
			else if(IC_Value2 <IC_Value1)
			{
				Difference = ((400-IC_Value1)+IC_Value2)+1;
				printf("difference:%d \n",Difference);
			}
			else
			{
				Error_Handler();
			}
			//frequency= TIM3 CLOCK /difference
			//In my case TIM3 clock is same as PCLK1 clock
			
			Frequency = (72000000/72)/Difference;//calculate freq
			printf("Frequency:%d\n",Frequency);
			Is_First_Captured=0;//reset the capture index
		}
	}
}

main函数

int main(void)
{
  HAL_Init();
  
  /* Configure the system clock */
  SystemClock_Config();
  
  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_TIM1_Init();
  MX_TIM3_Init();
  MX_USART1_UART_Init();
  
 //start the Input capture in tinterrrupt mode
  HAL_TIM_IC_Start_IT(&htim3,TIM_CHANNEL_1);
  HAL_TIM_PWM_Start(&htim1,TIM_CHANNEL_1);
  printf("test \n");
  while (1)
  {
  
  }

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值