基于stm32f103c8t6超声波测距代码
时间: 2023-07-31 08:11:28 浏览: 107
以下是基于stm32f103c8t6超声波测距的代码:
```c
#include "stm32f10x.h"
#define HCSR04_TRIG_PIN GPIO_Pin_0 // 超声波触发引脚
#define HCSR04_ECHO_PIN GPIO_Pin_1 // 超声波回声引脚
void delay_us(uint32_t time);
int main(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_ICInitTypeDef TIM_ICInitStructure;
uint16_t prescalerValue = 0;
float distance = 0;
/* Enable peripheral clocks --------------------------------------------------*/
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
/* Configure GPIO -----------------------------------------------------------*/
GPIO_InitStructure.GPIO_Pin = HCSR04_TRIG_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = HCSR04_ECHO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/* TIM3 configuration ------------------------------------------------------*/
TIM_DeInit(TIM3);
prescalerValue = (uint16_t) (SystemCoreClock / 1000000) - 1;
TIM_TimeBaseStructure.TIM_Period = 65535;
TIM_TimeBaseStructure.TIM_Prescaler = prescalerValue;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
TIM_ICStructInit(&TIM_ICInitStructure);
TIM_ICInitStructure.TIM_Channel = TIM_Channel_1;
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
TIM_ICInitStructure.TIM_ICFilter = 0x0;
TIM_ICInit(TIM3, &TIM_ICInitStructure);
/* TIM enable counter ------------------------------------------------------*/
TIM_Cmd(TIM3, ENABLE);
while (1)
{
/* 发送一个10us的高电平脉冲 */
GPIO_SetBits(GPIOA, HCSR04_TRIG_PIN);
delay_us(10);
GPIO_ResetBits(GPIOA, HCSR04_TRIG_PIN);
/* 等待回声引脚变为高电平 */
while (GPIO_ReadInputDataBit(GPIOA, HCSR04_ECHO_PIN) == RESET);
/* 开始计时 */
TIM_SetCounter(TIM3, 0);
/* 等待回声引脚变为低电平 */
while (GPIO_ReadInputDataBit(GPIOA, HCSR04_ECHO_PIN) != RESET);
/* 停止计时 */
distance = (float) TIM_GetCounter(TIM3) / 58.0;
}
}
/**
* 延时函数,精度为1us
*/
void delay_us(uint32_t time)
{
uint32_t i = 0;
for (i = 0; i < time * 8; i++);
}
```
该代码使用了STM32的定时器TIM3和超声波测距模块,通过发送10us的高电平脉冲触发超声波测距模块,然后等待回声引脚变为高电平,开始计时,直到回声引脚变为低电平,停止计时。最后,通过计算计时器的数值得到距离。需要注意的是,该代码的距离单位为厘米。
阅读全文