基于stm32f13c8t6、HCSR04,写一个代码,实现超声波测距
时间: 2023-06-13 22:06:18 浏览: 149
以下是基于stm32f13c8t6和HCSR04的超声波测距代码,可以参考:
```C
#include "stm32f10x.h"
#include "delay.h"
#define TRIG_PIN GPIO_Pin_0
#define ECHO_PIN GPIO_Pin_1
#define TRIG_PORT GPIOA
#define ECHO_PORT GPIOA
void HCSR04_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = TRIG_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(TRIG_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = ECHO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(ECHO_PORT, &GPIO_InitStructure);
}
float HCSR04_GetDistance(void)
{
u32 start_time = 0, end_time = 0;
float distance = 0;
GPIO_SetBits(TRIG_PORT, TRIG_PIN);
delay_us(10);
GPIO_ResetBits(TRIG_PORT, TRIG_PIN);
while(GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) == RESET);
start_time = SysTick->VAL;
while(GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) == SET);
end_time = SysTick->VAL;
if(end_time > start_time)
{
distance = (float)(end_time - start_time) * 100 / 72 / 2;
}
else
{
distance = (float)(start_time - end_time) * 100 / 72 / 2;
}
return distance;
}
int main(void)
{
HCSR04_Init();
Delay_Init();
while(1)
{
float distance = HCSR04_GetDistance();
printf("Distance: %.2f cm\r\n", distance);
delay_ms(500);
}
}
```
需要注意的是,该代码使用了自己编写的一个延时库delay.h,如果没有的话需要自行编写。此外,需要将printf函数与串口进行绑定,否则无法输出结果。
阅读全文