float Hcsr04GetLength(void ) { u32 t = 0; int i = 0; float lengthTemp = 0; float sum = 0; while(i!=5) { TRIG_Send = 1; delay_us(20); TRIG_Send = 0; while(ECHO_Reci == 0); OpenTimerForHc(); i = i + 1; while(ECHO_Reci == 1); CloseTimerForHc(); t = GetEchoTimer(); lengthTemp = ((float)t/58.0);//cm sum = lengthTemp + sum ; } lengthTemp = sum/5.0; return lengthTemp; } 将这个函数,改为标准库函数进行中断实现超声波测距
时间: 2023-12-12 10:02:34 浏览: 76
这个函数使用了延时函数和自定义的定时器函数,需要将其改为使用标准库函数进行中断实现。
以下是改写后的函数:
```
#include "stm32f10x.h"
#define TRIG_Send GPIO_Pin_0
#define ECHO_Reci GPIO_Pin_1
TIM_ICInitTypeDef TIM_ICInitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
void Hcsr04Init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
GPIO_InitStructure.GPIO_Pin = TRIG_Send;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = ECHO_Reci;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOA, &GPIO_InitStructure);
TIM_ICStructInit(&TIM_ICInitStructure);
TIM_ICInitStructure.TIM_ICFilter = 0x0F;
TIM_ICInit(TIM2, &TIM_ICInitStructure);
TIM_Cmd(TIM2, ENABLE);
}
float Hcsr04GetLength(void)
{
uint32_t t = 0;
int i = 0;
float lengthTemp = 0;
float sum = 0;
while(i != 5)
{
TRIG_Send = 1;
delay_us(20);
TRIG_Send = 0;
TIM_SetCounter(TIM2, 0);
while(GPIO_ReadInputDataBit(GPIOA, ECHO_Reci) == 0);
TIM_Cmd(TIM2, ENABLE);
while(GPIO_ReadInputDataBit(GPIOA, ECHO_Reci) == 1);
TIM_Cmd(TIM2, DISABLE);
t = TIM_GetCapture1(TIM2);
lengthTemp = ((float)t/58.0); // cm
sum = lengthTemp + sum;
i = i + 1;
}
lengthTemp = sum/5.0;
return lengthTemp;
}
```
在这个改写后的函数中,使用了标准库函数来进行定时器和中断的配置,实现了超声波测距的功能。
阅读全文