使用STM32F103ZET6和HC-SR04开发超声波测距
时间: 2024-05-14 15:15:09 浏览: 169
步骤如下:
1.连接硬件:将HC-SR04的VCC接到STM32F103ZET6的5V,GND接到GND,Trig接到STM32F103ZET6的PB10,Echo接到STM32F103ZET6的PB11。
2.配置STM32F103ZET6的GPIO:将PB10配置为输出模式,PB11配置为输入模式。
3.编写程序:使用定时器来生成10us的高电平,然后将Trig引脚拉高,等待10us后拉低。然后等待Echo引脚变高,开始计时,直到Echo引脚变低,停止计时。根据计时器的值计算距离并输出到串口。
下面是代码示例:
```
#include "stm32f10x.h"
#include "stdio.h"
#define TRIG_PIN GPIO_Pin_10
#define ECHO_PIN GPIO_Pin_11
#define TRIG_PORT GPIOB
#define ECHO_PORT GPIOB
void TIM3_init(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
TIM_TimeBaseInitStruct.TIM_Prescaler = (SystemCoreClock/1000000) - 1; //1us per tick
TIM_TimeBaseInitStruct.TIM_Period = 0xFFFF;
TIM_TimeBaseInitStruct.TIM_ClockDivision = 0;
TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStruct);
TIM_Cmd(TIM3, ENABLE);
}
void delay_us(uint32_t us)
{
TIM_SetCounter(TIM3, 0);
while(TIM_GetCounter(TIM3) < us);
}
float get_distance(void)
{
uint32_t time_start, time_end;
float distance;
GPIO_ResetBits(TRIG_PORT, TRIG_PIN);
delay_us(2);
GPIO_SetBits(TRIG_PORT, TRIG_PIN);
delay_us(10);
GPIO_ResetBits(TRIG_PORT, TRIG_PIN);
while(GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) == RESET);
time_start = TIM_GetCounter(TIM3);
while(GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) == SET);
time_end = TIM_GetCounter(TIM3);
if(time_end > time_start)
{
distance = (float)(time_end - time_start) * 0.017; //calculate distance in cm
}
else
{
distance = 0;
}
return distance;
}
int main(void)
{
USART_InitTypeDef USART_InitStruct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO | RCC_APB2Periph_USART1, ENABLE);
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.GPIO_Pin = TRIG_PIN;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(TRIG_PORT, &GPIO_InitStruct);
GPIO_InitStruct.GPIO_Pin = ECHO_PIN;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(ECHO_PORT, &GPIO_InitStruct);
USART_InitStruct.USART_BaudRate = 115200;
USART_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_InitStruct.USART_StopBits = USART_StopBits_1;
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStruct.USART_Mode = USART_Mode_Tx;
USART_Init(USART1, &USART_InitStruct);
USART_Cmd(USART1, ENABLE);
TIM3_init();
while(1)
{
float distance = get_distance();
printf("Distance: %.2f cm\n", distance);
delay_us(500000);
}
}
```
阅读全文