stm32f103rct6超声波代码生成
时间: 2023-10-12 12:06:06 浏览: 93
以下是一个基于STM32F103RCT6的超声波测距代码生成的示例,你可以根据自己的需求进行修改和优化。
```c
#include "stm32f10x.h"
#include "stm32f10x_gpio.h"
#include "stm32f10x_rcc.h"
#include "misc.h"
#define TRIG_PIN GPIO_Pin_6
#define ECHO_PIN GPIO_Pin_7
#define TRIG_PORT GPIOA
#define ECHO_PORT GPIOA
#define TIM_PERIOD 0xFFFF // Timer 2 计数器周期
void delay_us(uint32_t nus)
{
uint32_t ticks;
ticks = (SystemCoreClock / 1000000) * nus;
while(ticks--);
}
void TIM2_IRQHandler(void)
{
if(TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
GPIO_ResetBits(TRIG_PORT, TRIG_PIN); // 将 Trig 引脚拉低
}
}
float GetDistance(void)
{
uint32_t time_start, time_end;
float distance;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
TIM_OCInitTypeDef TIM_OCInitStruct;
// 初始化 TIM2
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseInitStruct.TIM_Period = TIM_PERIOD;
TIM_TimeBaseInitStruct.TIM_Prescaler = (SystemCoreClock / 1000000) - 1;
TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStruct);
// 初始化 TIM2 Channel1 用于发送超声波
TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStruct.TIM_Pulse = 10; // 10us 高电平
TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM2, &TIM_OCInitStruct);
// 初始化 GPIOA6 和 GPIOA7
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_IN_FLOATING;
GPIO_Init(ECHO_PORT, &GPIO_InitStructure);
// 发送超声波
GPIO_SetBits(TRIG_PORT, TRIG_PIN);
delay_us(10);
GPIO_ResetBits(TRIG_PORT, TRIG_PIN);
// 等待 Echo 引脚变高
while(GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) == RESET);
// 记录 Echo 引脚变高时的计数值
TIM_Cmd(TIM2, ENABLE);
while(GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) != RESET);
TIM_Cmd(TIM2, DISABLE);
time_start = TIM_GetCounter(TIM2);
// 等待 Echo 引脚变低
while(GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) != RESET);
// 记录 Echo 引脚变低时的计数值
TIM_Cmd(TIM2, ENABLE);
while(GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) == RESET);
TIM_Cmd(TIM2, DISABLE);
time_end = TIM_GetCounter(TIM2);
// 计算距离
distance = (float)(time_end - time_start) * 0.017; // 声速为 340m/s,距离 = 时间 * 声速 / 2
// 关闭 TIM2 和 GPIOA6
TIM_Cmd(TIM2, DISABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, DISABLE);
GPIO_ResetBits(TRIG_PORT, TRIG_PIN);
GPIO_InitStructure.GPIO_Pin = TRIG_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(TRIG_PORT, &GPIO_InitStructure);
return distance;
}
```
在主函数中,你可以通过调用 `GetDistance()` 函数来获取超声波测距的距离值。例如:
```c
int main(void)
{
float distance;
// 初始化系统时钟和其他外设
// ...
while(1)
{
distance = GetDistance(); // 获取距离值
// 处理距离值
// ...
}
}
```
阅读全文