使用定时器tim2。
时间: 2023-07-30 15:04:27 浏览: 84
好的,那么针对您的问题,我可以给您提供以下使用TIM2测距的代码:
```c++
#include "stm32f10x.h"
#include "delay.h"
#define Trig_Pin GPIO_Pin_6
#define Echo_Pin GPIO_Pin_7
#define Trig_Port GPIOA
#define Echo_Port GPIOA
void TIM2_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseInitStruct.TIM_Prescaler = SystemCoreClock / 1000000 - 1;
TIM_TimeBaseInitStruct.TIM_Period = 0xFFFF;
TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStruct);
}
float HC_SR04_GetDistance(void)
{
uint32_t cnt = 0;
float distance = 0;
GPIO_ResetBits(Trig_Port, Trig_Pin);
TIM_Cmd(TIM2, DISABLE);
TIM_SetCounter(TIM2, 0);
Delay_us(2);
GPIO_SetBits(Trig_Port, Trig_Pin);
TIM_Cmd(TIM2, ENABLE);
while(GPIO_ReadInputDataBit(Echo_Port, Echo_Pin) == RESET);
while(GPIO_ReadInputDataBit(Echo_Port, Echo_Pin) == SET)
{
cnt = TIM_GetCounter(TIM2);
}
TIM_Cmd(TIM2, DISABLE);
distance = (float)cnt * 0.017 / 2;
return distance;
}
```
注:以上代码需要先进行库文件的导入和配置,并且需要自行添加头文件delay.h,并实现其中的Delay_us()函数。同时,需要在main函数中调用TIM2_Configuration()进行定时器的初始化。
阅读全文