目录
一.题目要求
因为此题需要同一个定时器的两个通道做采集,所以无可避免的会有冲突,本文给出了一种解决方案,以供借鉴。
二.CubeMX的配置
因为我的PA1引脚坏了,所以使用了A2和A3两个引脚
输入捕获模式的配置,80分频,上升沿触发
为了方便测量,输出了两路pwm波,以下为配置。
三.代码的编写
变量的定义
uint32_t Channel1_buf,Channel2_buf;
double Channel1_fre,Channel2_fre;
unsigned char Channel1_count,Channel2_count;
PWM波输出函数的编写
void PWM1_Out(uint32_t fre)
{
htim3.Init.Period=1000000/fre-1;
HAL_TIM_Base_Init(&htim3);
HAL_TIM_PWM_Start(&htim3,TIM_CHANNEL_1);
__HAL_TIM_SetCompare(&htim3,TIM_CHANNEL_1,500);
}
void PWM2_Out(uint32_t fre)
{
htim4.Init.Period=1000000/fre-1;
HAL_TIM_Base_Init(&htim4);
HAL_TIM_PWM_Start(&htim4,TIM_CHANNEL_1);
__HAL_TIM_SetCompare(&htim4,TIM_CHANNEL_1,500);
}
捕捉函数的编写
void Channel1_Capture(void)
{
switch(Channel1_count)
{
case 0:
Channel1_count++;
TIM_SET_CAPTUREPOLARITY(&htim2,TIM_CHANNEL_3,TIM_ICPOLARITY_RISING);
break;
case 3: Channel1_count=0;
Channel1_fre=1000000.00/Channel1_buf;
break;
}
}
void Channel2_Capture(void)
{
switch(Channel2_count)
{
case 0:
Channel2_count++;
TIM_SET_CAPTUREPOLARITY(&htim2,TIM_CHANNEL_4,TIM_ICPOLARITY_RISING);
break;
case 3: Channel2_count=0;
Channel2_fre=1000000.00/Channel2_buf;
break;
}
}
捕捉中断函数的编写
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef*htim)
{
if(htim->Channel== HAL_TIM_ACTIVE_CHANNEL_3 )
{
switch(Channel1_count)
{
case 1:
HAL_TIM_IC_Stop(&htim2,TIM_CHANNEL_4);
Channel1_count++;
__HAL_TIM_SetCounter(&htim2,0);
HAL_TIM_IC_Start_IT(&htim2,TIM_CHANNEL_3);
break;
case 2:Channel1_count++;
Channel1_buf=HAL_TIM_ReadCapturedValue(htim,TIM_CHANNEL_3);
HAL_TIM_IC_Stop_IT(&htim2,TIM_CHANNEL_3);
HAL_TIM_IC_Start_IT(&htim2,TIM_CHANNEL_4);
break;
}
}
if(htim->Channel== HAL_TIM_ACTIVE_CHANNEL_4)
{
switch(Channel2_count)
{
case 1:
HAL_TIM_IC_Stop(&htim2,TIM_CHANNEL_3);
Channel2_count++;
__HAL_TIM_SetCounter(&htim2,0);
HAL_TIM_IC_Start_IT(&htim2,TIM_CHANNEL_4);
break;
case 2:Channel2_count++;
Channel2_buf=HAL_TIM_ReadCapturedValue(htim,TIM_CHANNEL_4);
HAL_TIM_IC_Start_IT(&htim2,TIM_CHANNEL_3);
HAL_TIM_IC_Stop_IT(&htim2,TIM_CHANNEL_4);
break;
}
}
}
显示函数的编写
void LCD_Disp(void)
{
char str[100];
LCD_SetBackColor(Blue);
LCD_SetTextColor(White);
sprintf(str,"Ch(1):%.2f Hz",Channel1_fre);
LCD_DisplayStringLine(Line2,str);
sprintf(str,"Ch(2):%.2f Hz",Channel2_fre);
LCD_DisplayStringLine(Line6,str);
}
主函数的编写
HAL_TIM_IC_Start_IT(&htim2,TIM_CHANNEL_3);
HAL_TIM_IC_Start_IT(&htim2,TIM_CHANNEL_4);
LCD_Init();
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
LCD_Clear(Blue);
while (1)
{
PWM2_Out(1000);
PWM1_Out(500);
Channel2_Capture();
Channel1_Capture();
LCD_Disp();
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}