STM32单片机读取超声波传感器距离程序
时间: 2023-07-28 07:16:22 浏览: 49
以下是基于STM32单片机读取超声波传感器距离的程序:
```c
#include "stm32f10x.h"
#define TRIG_PIN GPIO_Pin_0
#define ECHO_PIN GPIO_Pin_1
#define TRIG_PORT GPIOA
#define ECHO_PORT GPIOA
int main()
{
// 初始化GPIO口
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
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);
GPIO_InitStructure.GPIO_Pin = ECHO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(ECHO_PORT, &GPIO_InitStructure);
// 初始化定时器
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
TIM_TimeBaseStructure.TIM_Prescaler = 72 - 1;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
// 等待定时器启动
TIM_Cmd(TIM2, ENABLE);
while (TIM_GetFlagStatus(TIM2, TIM_FLAG_Update) == RESET);
while (1)
{
// 触发超声波
GPIO_ResetBits(TRIG_PORT, TRIG_PIN);
TIM_SetCounter(TIM2, 0);
while (TIM_GetFlagStatus(TIM2, TIM_FLAG_Update) == RESET);
GPIO_SetBits(TRIG_PORT, TRIG_PIN);
// 等待超声波返回
while (GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) == RESET);
TIM_SetCounter(TIM2, 0);
while (GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) == SET);
// 计算距离
uint16_t time = TIM_GetCounter(TIM2);
float distance = time / 58.0f;
// 输出距离
printf("distance: %.2f cm\n", distance);
// 延时一段时间
for (int i = 0; i < 1000000; i++);
}
}
```
该程序使用了STM32的定时器和GPIO口来控制超声波传感器的触发和接收,并通过计算得出距离。其中,TRIG_PIN和ECHO_PIN分别为超声波传感器的触发和接收引脚,TRIG_PORT和ECHO_PORT为对应的GPIO端口。在主循环中,程序会不断地读取超声波传感器距离并输出。