stm32 超声波代码
时间: 2023-07-09 07:30:05 浏览: 155
以下是 STM32 的超声波测距代码,供参考:
```
#include "stm32f10x.h"
#define ECHO_PIN GPIO_Pin_0
#define ECHO_PORT GPIOA
#define TRIG_PIN GPIO_Pin_1
#define TRIG_PORT GPIOA
void init_gpio(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/* Enable GPIOA clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
/* Configure PA0 as input floating */
GPIO_InitStructure.GPIO_Pin = ECHO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(ECHO_PORT, &GPIO_InitStructure);
/* Configure PA1 as push-pull output */
GPIO_InitStructure.GPIO_Pin = TRIG_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(TRIG_PORT, &GPIO_InitStructure);
}
void delay_us(uint32_t us)
{
/* Configure SysTick */
SysTick->LOAD = (us * SystemCoreClock / 1000000UL) - 1;
SysTick->VAL = 0;
SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_ENABLE_Msk;
/* Wait until the SysTick timer reaches 0 */
while (!(SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk));
/* Disable SysTick */
SysTick->CTRL = 0;
}
float get_distance(void)
{
uint32_t pulse_width;
float distance;
/* Send a 10us pulse to the TRIG pin */
GPIO_SetBits(TRIG_PORT, TRIG_PIN);
delay_us(10);
GPIO_ResetBits(TRIG_PORT, TRIG_PIN);
/* Wait for the ECHO pin to go high */
while (!GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN));
/* Start the timer */
TIM_Cmd(TIM2, ENABLE);
/* Wait for the ECHO pin to go low */
while (GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN));
/* Stop the timer */
TIM_Cmd(TIM2, DISABLE);
/* Calculate the pulse width in microseconds */
pulse_width = TIM_GetCounter(TIM2);
/* Calculate the distance in centimeters */
distance = pulse_width / 58.0;
return distance;
}
int main(void)
{
float distance;
/* Initialize GPIO */
init_gpio();
/* Initialize TIM2 */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Period = 0xFFFFFFFF;
TIM_TimeBaseStructure.TIM_Prescaler = SystemCoreClock / 1000000UL - 1;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
while (1)
{
/* Measure the distance */
distance = get_distance();
/* Do something with the distance */
// ...
}
}
```
这个代码使用的是 STM32F103C8T6 开发板,使用 TIM2 计时器来测量超声波回波的脉冲宽度,然后根据公式 `distance = pulse_width / 58.0` 计算距离。具体实现方式可参考代码注释。
阅读全文