由上图我们可以知道,高电平时间=t2-t1。在代码中,可以记录此时t1的时间然后再记录t2的时间,t2-t1,就是我们所想要的答案。
但是,还有更简单一点点的,当到达t1的时候,我们把定时器清零,然后直接读出t2,就是这个高电平的时间。
- 1.当TIM3的TIM_FLAG_CC1==1时,清除TIM3
void TIM3_IRQHandler(void)
{if(TIM_GetITStatus(TIM3,TIM_FLAG_CC1)==SET){TIM_SetCounter(TIM3,0);}TIM_ClearITPendingBit(TIM3,TIM_FLAG_CC1);
}
- 2.从波形图可以看出,刚开始检测的是上升沿,所以检测TIM_FLAG_CC1的时候是SET,到了第二步,波形开始下降,变为下降沿,此时我们就要更改一下检测的方式了,我们可以用到下面这个函数。
TIM_OC1PolarityConfig(TIM3,TIM_OCPolarity_Low);
//更改下次检测的极性为low(低电平)
void TIM3_IRQHandler(void)
{static unsigned char high_flag = 0;if(TIM_GetITStatus(TIM3,TIM_FLAG_CC1)==SET){if(high_flag == 0)//上升沿{high_flag = 1;TIM_SetCounter(TIM3,0);TIM_OC1PolarityConfig(TIM3,TIM_OCPolarity_Low);}else//下降沿{high_value = TIM_GetCounter(TIM3);TIM_OC1PolarityConfig(TIM3,TIM_OCPolarity_High);high_flag = 0;}}TIM_ClearITPendingBit(TIM3,TIM_FLAG_CC1);
}
- 3.每次到下一个波形的时候,都重新初始化一下high_value.
if(high_flag == 0)//上升沿
{high_flag = 1;high_value = 0;TIM_SetCounter(TIM3,0);TIM_OC1PolarityConfig(TIM3,TIM_OCPolarity_Low);
}
- 4.如果在main中,去使用了high_value,此时高电平还在不断输出,定时器也在运行,high_value仍会该改变,对于high_value的使用就不方便。所以我们需要限制一个条件,当我们使用high_value的时候,不要去重新写high_value了。
void TIM3_IRQHandler(void)
{static unsigned char high_flag = 0;if(high_complete_flag == 0){if(TIM_GetITStatus(TIM3,TIM_FLAG_CC1)==SET){if(high_flag == 0)//上升沿{high_flag = 1;high_value = 0;TIM_SetCounter(TIM3,0);TIM_OC1PolarityConfig(TIM3,TIM_OCPolarity_Low);}else//下降沿{high_value = TIM_GetCounter(TIM3);TIM_OC1PolarityConfig(TIM3,TIM_OCPolarity_High);high_flag = 0;high_complete_flag = 1;}}}TIM_ClearITPendingBit(TIM3,TIM_FLAG_CC1);
}
在使用high_value之前,让high_complete_flag = 0;这样之后时,high_value就不会变了。
main
int main(void)
{TIM2_PWM_Configuration();//PWM周期为20msTIM3_InputCaputure_Configuration();//PA1:发出《————》PA6:接收Uart1_Configuration();TIM_SetCompare2(TIM2,10000);//占空比为50%,即10ms高电平while(1){if(high_complete_flag == 1){printf("%d us",high_value);high_complete_flag = 0;}Delay_s(10);}}