1.硬件
2.软件
#include "sys.h"
#include "delay.h"
#include "led.h"
#include "uart1.h"
#include "hcsr04.h"
int main(void)
{
HAL_Init();
stm32_clock_init(RCC_PLL_MUL9);
led_init();
uart1_init(115200);
hcsr04_init();
printf("hello world!\r\n");
while(1)
{
printf("dis: %.2f\r\n", hcsr04_get_length());
delay_ms(1000);
}
}
#include "hcsr04.h"
#include "delay.h"
TIM_HandleTypeDef tim2_handle = {0};
void tim2_init(void)
{
tim2_handle.Instance = TIM2;
tim2_handle.Init.Prescaler = 72 - 1;
tim2_handle.Init.Period = 65536 - 1;
tim2_handle.Init.CounterMode = TIM_COUNTERMODE_UP;
tim2_handle.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
HAL_TIM_Base_Init(&tim2_handle);
}
void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim)
{
if(htim->Instance == TIM2)
{
__HAL_RCC_TIM2_CLK_ENABLE();
}
}
void tim2_start(void)
{
HAL_TIM_Base_Start(&tim2_handle);
}
void tim2_stop(void)
{
HAL_TIM_Base_Stop(&tim2_handle);
}
uint16_t tim2_get_cnt(void)
{
return __HAL_TIM_GetCounter(&tim2_handle);
}
void tim2_set_cnt(uint16_t val)
{
__HAL_TIM_SetCounter(&tim2_handle, val);
}
void hcsr04_gpio_init(void)
{
GPIO_InitTypeDef gpio_initstruct;
TRIG_GPIO_CLK_ENABLE();
ECHO_GPIO_CLK_ENABLE();
gpio_initstruct.Pin = TRIG_PIN;
gpio_initstruct.Mode = GPIO_MODE_OUTPUT_PP;
gpio_initstruct.Pull = GPIO_NOPULL;
gpio_initstruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(TRIG_PORT, &gpio_initstruct);
gpio_initstruct.Pin = ECHO_PIN;
gpio_initstruct.Mode = GPIO_MODE_INPUT;
HAL_GPIO_Init(ECHO_PORT, &gpio_initstruct);
}
void hcsr04_init(void)
{
tim2_init();
hcsr04_gpio_init();
}
float hcsr04_get_length(void)
{
uint16_t total_time = 0;
float distance = 0;
TRIG_HIGH();
delay_us(15);
TRIG_LOW();
while(ECHO_STATUS() == GPIO_PIN_RESET);
tim2_start();
tim2_set_cnt(0);
while(ECHO_STATUS() == GPIO_PIN_SET);
tim2_stop();
total_time = tim2_get_cnt();
distance = total_time * 0.01715;
return distance;
}
#ifndef __HCSR04_H__
#define __HCSR04_H__
#include "sys.h"
#define TRIG_PORT GPIOB
#define TRIG_PIN GPIO_PIN_6
#define TRIG_GPIO_CLK_ENABLE() __HAL_RCC_GPIOB_CLK_ENABLE()
#define TRIG_HIGH() HAL_GPIO_WritePin(TRIG_PORT, TRIG_PIN, GPIO_PIN_SET)
#define TRIG_LOW() HAL_GPIO_WritePin(TRIG_PORT, TRIG_PIN, GPIO_PIN_RESET)
#define ECHO_PORT GPIOB
#define ECHO_PIN GPIO_PIN_7
#define ECHO_GPIO_CLK_ENABLE() __HAL_RCC_GPIOB_CLK_ENABLE()
#define ECHO_STATUS() HAL_GPIO_ReadPin(ECHO_PORT, ECHO_PIN)
void hcsr04_init(void);
float hcsr04_get_length(void);
#endif
3.实物效果
HC-SR04 | STM32 |
---|
Trig | PB6 |
Echo | PB7 |
VCC | 5V |
GND | GND |
ST-Link下载方式
- 实验现象
通过USB转TTL串口模块,将STM32单片机与电脑连接,打开串口软件,设置波特率115200,可以看到串口打印处超声波模块所测量的距离。