蓝桥杯的输入捕获较为简单,基本不涉及溢出的问题。所以这里就不介绍溢出了。文末有源码。
一、Cubemx配置
二、代码编写
1.在捕获回调函数中
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
if(htim->Instance==TIM3)
{
switch(count)
{
case 1:
{
jishu1=__HAL_TIM_GET_COUNTER(&htim3);
__HAL_TIM_SET_CAPTUREPOLARITY(&htim3, TIM_CHANNEL_1, TIM_INPUTCHANNELPOLARITY_FALLING);
count++;
break;
}
case 2:
{
jishu2=__HAL_TIM_GET_COUNTER(&htim3);
__HAL_TIM_SET_CAPTUREPOLARITY(&htim3, TIM_CHANNEL_1, TIM_INPUTCHANNELPOLARITY_RISING);
count++;
break;
}
case 3:
{
jishu3=__HAL_TIM_GET_COUNTER(&htim3);
count++;
HAL_TIM_IC_Stop_IT(&htim3,TIM_CHANNEL_1);
break;
}
}
}
}
2.在main函数中
LCD_Init();
LCD_Clear(White);
HAL_TIM_IC_Stop_IT(&htim3, TIM_CHANNEL_1);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
switch(count)
{
case 0:
{
__HAL_TIM_SET_COUNTER(&htim3, 0);
HAL_TIM_IC_Start_IT(&htim3, TIM_CHANNEL_1);
__HAL_TIM_SET_CAPTUREPOLARITY(&htim3, TIM_CHANNEL_1, TIM_INPUTCHANNELPOLARITY_RISING);
count++;
break;
}
case 4:
{
fre=1000000.0/(jishu3-jishu1);
zkb=(jishu2-jishu1)*100.0/(jishu3-jishu1);
// 频率为占空比为
sprintf(buff,"zkb:%.2f%% fre:%.2f",zkb,fre);
LCD_DisplayStringLine(Line4, buff);
count=0;
break;
}
}
}
/* USER CODE END 3 */
}
三、现象
通过调节开发版上的旋钮改变占空比跟频率
小编的源码输入捕获源码