STM32,hcsr04超声波测距模块c语言代码
时间: 2023-08-16 20:07:12 浏览: 121
超声波测距模块 c语言代码
好的,以下是HCSR04超声波测距模块的STM32的C语言代码:
```C
#include "stm32f10x.h"
#include "stdio.h"
#include "delay.h"
#define Trig GPIO_Pin_2
#define Echo GPIO_Pin_3
void HC_SR04_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = Trig;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = Echo;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_ResetBits(GPIOA, Trig);
}
void HC_SR04_Trig(void)
{
GPIO_SetBits(GPIOA, Trig);
delay_us(10);
GPIO_ResetBits(GPIOA, Trig);
}
float HC_SR04_Get_Distance(void)
{
uint16_t i = 0;
float Distance = 0;
uint32_t temp = 0;
HC_SR04_Trig();
while(GPIO_ReadInputDataBit(GPIOA, Echo) == RESET)
{
i++;
delay_us(1);
if(i > 8000)
return -1;
}
TIM_Cmd(TIM2, ENABLE);
TIM_SetCounter(TIM2, 0);
while(GPIO_ReadInputDataBit(GPIOA, Echo) == SET)
{
temp = TIM_GetCounter(TIM2);
if(temp > 58000)
break;
}
TIM_Cmd(TIM2, DISABLE);
Distance = (float)temp / 58.0;
return Distance;
}
int main(void)
{
float distance = 0;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
TIM_TimeBaseStructure.TIM_Prescaler = 71;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
HC_SR04_Init();
delay_init();
while(1)
{
distance = HC_SR04_Get_Distance();
if(distance != -1)
{
printf("distance: %.2f cm\n", distance);
}
delay_ms(500);
}
}
```
这段代码使用了STM32的定时器来测量超声波从发送到接收的时间,并通过简单的公式将时间转换为距离。同时,这个例子也演示了如何使用USART向电脑终端输出距离信息。同样需要注意超声波测距模块与STM32的接线,以及Trig和Echo的定义是否正确。
阅读全文