stm32超声波测距代码
时间: 2023-07-02 10:23:17 浏览: 38
基于STM32F103C8T6超声波测距源码及接线(已调),stm32超声波测距代码,C/C++
5星 · 资源好评率100%
以下是一个简单的 stm32 超声波测距代码:
```c
#include "stm32f10x.h"
#define TRIG_PIN GPIO_Pin_0
#define TRIG_PORT GPIOA
#define ECHO_PIN GPIO_Pin_1
#define ECHO_PORT GPIOA
void delay_us(uint32_t nus)
{
uint32_t i;
for (i = 0; i < nus * 8; i++);
}
void delay_ms(uint32_t nms)
{
uint32_t i;
for (i = 0; i < nms * 8000; i++);
}
void send_trigger_pulse(void)
{
GPIO_WriteBit(TRIG_PORT, TRIG_PIN, Bit_SET);
delay_us(10);
GPIO_WriteBit(TRIG_PORT, TRIG_PIN, Bit_RESET);
}
float measure_distance(void)
{
uint32_t start_tick = 0, end_tick = 0;
float distance = 0;
while (GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) == RESET);
start_tick = TIM_GetCounter(TIM2);
while (GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) == SET);
end_tick = TIM_GetCounter(TIM2);
distance = (float)(end_tick - start_tick) * 1.7 / 100.0;
return distance;
}
int main(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = TRIG_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(TRIG_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = ECHO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(ECHO_PORT, &GPIO_InitStructure);
TIM_TimeBaseInitStructure.TIM_Period = 0xFFFF;
TIM_TimeBaseInitStructure.TIM_Prescaler = 71;
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStructure);
TIM_Cmd(TIM2, ENABLE);
while (1)
{
send_trigger_pulse();
delay_ms(50);
float distance = measure_distance();
// Do something with the measured distance
}
}
```
这个代码使用 TIM2 来计算超声波的回波时间,通过计算回波时间来计算距离。TRIG_PIN 是超声波发射器的引脚,ECHO_PIN 是超声波接收器的引脚。在 main 函数中,我们使用一个死循环来循环测量距离。你可以根据实际情况修改 delay_ms 的参数来控制测量频率。
阅读全文