基于STM32的hc-sr04超声波测距模块的代码
时间: 2023-09-27 19:11:14 浏览: 147
以下是基于STM32的hc-sr04超声波测距模块的代码示例:
```c
#include "stm32f10x.h"
#define Trig_Pin GPIO_Pin_0
#define Echo_Pin GPIO_Pin_1
#define Trig_Port GPIOC
#define Echo_Port GPIOC
void TIM2_Configuration(void);
float ultrasonic_measure(void);
int main(void)
{
float distance;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, 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_IN_FLOATING;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(Echo_Port, &GPIO_InitStruct);
TIM2_Configuration();
while(1)
{
distance = ultrasonic_measure();
}
}
void TIM2_Configuration(void)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
TIM_TimeBaseInitStruct.TIM_Prescaler = 72 - 1;
TIM_TimeBaseInitStruct.TIM_Period = 0xFFFF;
TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStruct);
TIM_OCInitTypeDef TIM_OCInitStruct;
TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OCInitStruct.TIM_Pulse = 0;
TIM_OC1Init(TIM2, &TIM_OCInitStruct);
TIM_Cmd(TIM2, ENABLE);
}
float ultrasonic_measure(void)
{
uint16_t TIM2_CountStart, TIM2_CountEnd;
float Distance;
GPIO_ResetBits(Trig_Port, Trig_Pin);
TIM_SetCounter(TIM2, 0);
while(TIM_GetCounter(TIM2) < 10); // delay 10us
GPIO_SetBits(Trig_Port, Trig_Pin);
while(GPIO_ReadInputDataBit(Echo_Port, Echo_Pin) == RESET);
TIM_Cmd(TIM2, ENABLE);
while(GPIO_ReadInputDataBit(Echo_Port, Echo_Pin) == SET);
TIM_Cmd(TIM2, DISABLE);
TIM2_CountStart = TIM2->CCR1;
TIM2_CountEnd = TIM_GetCapture1(TIM2);
Distance = (float)(TIM2_CountEnd - TIM2_CountStart) * 0.01715f; // Distance = (High level time * sound velocity (340M/S) / 2)
return Distance;
}
```
代码中使用了STM32的定时器TIM2进行计时,测量距离的原理是通过发送一个10us的高电平脉冲触发hc-sr04模块,然后接收返回的超声波信号并测量高电平持续时间,最后通过公式计算出距离。需要注意的是,本示例中使用的是72MHz的系统时钟,如果系统时钟不同,需要相应地修改计时器的预分频值。
阅读全文