stm32f407 hc-sr04超声波测距代码
时间: 2023-05-30 12:02:32 浏览: 527
STM32超声波测距代码-HC-SR04.zip
4星 · 用户满意度95%
以下是使用STM32F407和HC-SR04超声波测距模块的示例代码:
```c
#include "stm32f4xx.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_rcc.h"
#include "stm32f4xx_tim.h"
#include "misc.h"
#define TRIG_PIN GPIO_Pin_0
#define ECHO_PIN GPIO_Pin_1
#define GPIO_PORT GPIOA
uint32_t distance = 0;
void GPIO_Configuration(void) {
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = TRIG_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_Init(GPIO_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_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_Init(GPIO_PORT, &GPIO_InitStructure);
}
void TIM_Configuration(void) {
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructure.TIM_Period = 0xFFFFFFFF;
TIM_TimeBaseStructure.TIM_Prescaler = (uint16_t)(SystemCoreClock / 1000000) - 1;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
TIM_ICInitTypeDef TIM_ICInitStructure;
TIM_ICInitStructure.TIM_Channel = TIM_Channel_2;
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
TIM_ICInitStructure.TIM_ICFilter = 0x0;
TIM_ICInit(TIM2, &TIM_ICInitStructure);
TIM_Cmd(TIM2, ENABLE);
}
uint32_t GetDistance(void) {
GPIO_SetBits(GPIO_PORT, TRIG_PIN);
Delay_us(10);
GPIO_ResetBits(GPIO_PORT, TRIG_PIN);
uint32_t start_time = 0;
uint32_t end_time = 0;
uint32_t timeout = 0;
while (GPIO_ReadInputDataBit(GPIO_PORT, ECHO_PIN) == RESET) {
if (++timeout > 1000000) {
return 0xFFFFFFFF;
}
}
start_time = TIM_GetCounter(TIM2);
timeout = 0;
while (GPIO_ReadInputDataBit(GPIO_PORT, ECHO_PIN) == SET) {
if (++timeout > 1000000) {
return 0xFFFFFFFF;
}
}
end_time = TIM_GetCounter(TIM2);
if (end_time > start_time) {
distance = (end_time - start_time) * 10 / 58;
} else {
distance = (start_time - end_time) * 10 / 58;
}
return distance;
}
int main(void) {
GPIO_Configuration();
TIM_Configuration();
while (1) {
GetDistance();
}
return 0;
}
```
此代码初始化GPIO和定时器,然后在主循环中调用`GetDistance()`函数来获取测量到的距离。该函数使用超声波模块发送一个10微秒的脉冲,然后等待接收到回波。通过测量回波的时间来计算距离,并返回结果。在本例中,距离以毫米为单位表示。如果无法检测到回波或测量超时,则返回0xFFFFFFFF。
需要注意的是,在本例中,我们使用了定时器的输入捕获模式来测量回波的时间。我们使用TIM2的通道2来读取ECHO引脚的状态,并在上升沿触发捕获。此代码假设您已正确配置STM32F407的时钟源。如果您遇到问题,请参阅STM32F407参考手册。
阅读全文