写出STM32F407配置HC-SR04代码,要求用串口通信输出测量结果
时间: 2024-06-07 12:05:15 浏览: 90
好的,以下是代码实现:
#include "stm32f4xx.h"
#include "stdio.h"
#define TRIG_Pin GPIO_Pin_13
#define TRIG_Port GPIOE
#define ECHO_Pin GPIO_Pin_14
#define ECHO_Port GPIOE
uint32_t time;
void Delay_us(uint32_t us)
{
uint32_t ticks;
ticks = us * (SystemCoreClock / 1000000U);
while (ticks--);
}
void TIM5_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5, ENABLE);
TIM_TimeBaseStructure.TIM_Prescaler = (SystemCoreClock / 1000000U) - 1;
TIM_TimeBaseStructure.TIM_Period = 0xFFFFFFFF;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM5, &TIM_TimeBaseStructure);
}
void HC_SR04_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE, ENABLE);
GPIO_InitStructure.GPIO_Pin = TRIG_Pin;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(TRIG_Port, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = ECHO_Pin;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(ECHO_Port, &GPIO_InitStructure);
}
float HC_SR04_Measure(void)
{
float distance;
uint32_t start_time = 0, stop_time = 0, measure_time = 0, over_time = 0;
TRIG_Port -> BSRRH = TRIG_Pin;
Delay_us(2);
TRIG_Port -> BSRRL = TRIG_Pin;
while ((ECHO_Port -> IDR & ECHO_Pin) == RESET);
start_time = TIM5 -> CNT;
while ((ECHO_Port -> IDR & ECHO_Pin) != RESET);
stop_time = TIM5 -> CNT;
measure_time = stop_time - start_time;
if (measure_time >= 58000)
{
over_time = 1;
}
distance = (float)measure_time / 58.0;
if (over_time)
{
distance = -1.0;
}
return distance;
}
int main(void)
{
char buff[32] = {0};
float distance = 0.0;
USART1_Configuration();
TIM5_Configuration();
HC_SR04_Configuration();
while(1)
{
distance = HC_SR04_Measure();
if (distance < 0.0)
{
sprintf(buff, "Measurement timeout!\r\n");
}
else
{
sprintf(buff, "Distance: %.2fcm\r\n", distance);
}
USART_puts(USART1, buff);
Delay_us(500000);
}
}
阅读全文