基于stm32f103rct6的超声波测距代码
时间: 2023-09-10 22:14:33 浏览: 145
表示有内部下拉电阻-stm32f103rct6之超声波测距(hc-sr04)测试篇
以下是基于STM32F103RCT6的超声波测距代码,使用的是TIM2模块作为计时器:
```c
#include "stm32f10x.h"
#define TRIG_PIN GPIO_Pin_8
#define ECHO_PIN GPIO_Pin_9
void GPIO_Configuration(void);
void TIM_Configuration(void);
int main(void)
{
uint32_t distance;
GPIO_Configuration();
TIM_Configuration();
while(1)
{
GPIO_SetBits(GPIOB, TRIG_PIN);
delay_us(10);
GPIO_ResetBits(GPIOB, TRIG_PIN);
while(!GPIO_ReadInputDataBit(GPIOB, ECHO_PIN));
TIM_Cmd(TIM2, ENABLE);
while(GPIO_ReadInputDataBit(GPIOB, ECHO_PIN));
TIM_Cmd(TIM2, DISABLE);
distance = TIM_GetCounter(TIM2) / 58;
TIM_SetCounter(TIM2, 0);
}
}
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = TRIG_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = ECHO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
void TIM_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
TIM_TimeBaseStructure.TIM_Prescaler = SystemCoreClock / 1000000 - 1;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
}
```
其中,`delay_us()`函数可以自己定义,实现微秒级延时。这段代码实现的是不断地进行超声波测距,每次测量完成后将距离存储在`distance`变量中。具体的超声波测距原理可以参考其他资料。
阅读全文