用stm32f103c8t6和超声波模块编写一段程序!
时间: 2023-07-29 09:11:26 浏览: 102
基于STM32F103C8T6超声波测距源码及接线(已调).zip
好的,这里提供一个简单的超声波测距程序,使用STM32F103C8T6和HC-SR04超声波模块,你可以参考一下:
```c
#include "stm32f10x.h"
#include "delay.h"
#define TRIG_PIN GPIO_Pin_0
#define ECHO_PIN GPIO_Pin_1
#define TRIG_PORT GPIOA
#define ECHO_PORT GPIOA
void delay_us(uint32_t us)
{
while (us--)
{
__NOP();
}
}
void HC_SR04_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
TIM_TimeBaseInitTypeDef TIM_InitStruct;
TIM_OCInitTypeDef TIM_OCInitStruct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
GPIO_InitStruct.GPIO_Pin = TRIG_PIN;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(TRIG_PORT, &GPIO_InitStruct);
GPIO_InitStruct.GPIO_Pin = ECHO_PIN;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(ECHO_PORT, &GPIO_InitStruct);
TIM_InitStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_InitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_InitStruct.TIM_Prescaler = 72 - 1;
TIM_InitStruct.TIM_Period = 0xFFFF;
TIM_TimeBaseInit(TIM2, &TIM_InitStruct);
TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OCInitStruct.TIM_Pulse = 0;
TIM_OC1Init(TIM2, &TIM_OCInitStruct);
TIM_Cmd(TIM2, ENABLE);
}
uint32_t HC_SR04_GetDistance(void)
{
uint32_t start_time, end_time;
float distance;
GPIO_SetBits(TRIG_PORT, TRIG_PIN);
delay_us(10);
GPIO_ResetBits(TRIG_PORT, TRIG_PIN);
while (GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) == RESET)
{
start_time = TIM_GetCounter(TIM2);
}
while (GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) == SET)
{
end_time = TIM_GetCounter(TIM2);
}
distance = (end_time - start_time) * 0.017;
return (uint32_t)distance;
}
int main(void)
{
uint32_t distance;
HC_SR04_Init();
while (1)
{
distance = HC_SR04_GetDistance();
delay_ms(500);
}
}
```
这段程序使用的是TIM2定时器来计算超声波传播时间,需要先初始化TIM2定时器和超声波模块的GPIO口,然后通过发送一个10us的脉冲来触发超声波模块,等待回波信号并计算出距离。需要注意的是,这段程序中的计算距离的公式是针对超声波在空气中传播的,如果你的场景不同可能需要做出调整。
阅读全文