帮我用c语言写基于stm32f103zet6单片机的hc-sr04模块的超声波测距的代码
时间: 2024-02-21 16:57:10 浏览: 80
超声波测距模块 c语言代码
好的,下面是基于STM32F103ZET6单片机的HC-SR04模块的超声波测距的代码,希望对你有帮助。
```c
#include "stm32f10x.h"
#include "delay.h"
#define TRIG GPIO_Pin_6
#define ECHO GPIO_Pin_7
void TIM3_Int_Init(u16 arr, u16 psc);
float Distance(void);
int main(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = TRIG;
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;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
TIM3_Int_Init(0xFFFF, 72 - 1);
while (1) {
float distance = Distance();
// 根据超声波测距测得的距离做出相应的操作
delay_ms(100);
}
}
void TIM3_Int_Init(u16 arr, u16 psc)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
TIM_TimeBaseStructure.TIM_Period = arr;
TIM_TimeBaseStructure.TIM_Prescaler = psc;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_Cmd(TIM3, ENABLE);
}
float Distance(void)
{
float distance;
u32 temp;
GPIO_SetBits(GPIOB, TRIG);
delay_us(20);
GPIO_ResetBits(GPIOB, TRIG);
while (!GPIO_ReadInputDataBit(GPIOB, ECHO));
TIM_SetCounter(TIM3, 0);
while (GPIO_ReadInputDataBit(GPIOB, ECHO));
temp = TIM_GetCounter(TIM3);
distance = (float)temp * 0.01715;
return distance;
}
void TIM3_IRQHandler(void)
{
if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET) {
TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
}
}
```
注:以上代码仅作参考,具体实现需要根据实际情况进行修改。
阅读全文