帮我用keil5写基于stm32f103zet6单片机的hc-sr04模块的超声波测距的代码
时间: 2024-04-26 17:25:22 浏览: 143
好的,下面是基于stm32f103zet6单片机的hc-sr04模块超声波测距的代码,使用Keil5编译:
```
#include "stm32f10x.h"
#include <stdio.h>
#define TRIG GPIO_Pin_5
#define ECHO GPIO_Pin_6
void delay_us(u32);
void delay_ms(u16);
int main(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
TIM_OCInitTypeDef TIM_OCInitStruct;
NVIC_InitTypeDef NVIC_InitStructure;
float distance = 0;
char str[16];
// 初始化GPIOB和TIM3
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
// 初始化GPIOB Pin5为输出模式和Pin6为输入模式
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为1MHz计数频率,计数器自动重载,预分频系数为71,计数模式为向上计数
TIM_TimeBaseInitStruct.TIM_Period = 0xFFFF;
TIM_TimeBaseInitStruct.TIM_Prescaler = 71;
TIM_TimeBaseInitStruct.TIM_ClockDivision = 0;
TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStruct);
// 配置TIM3的PWM模式为模式2,输出比较模式为PWM1
TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM2;
TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStruct.TIM_Pulse = 0;
TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM3, &TIM_OCInitStruct);
// 配置TIM3中断
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
// 启动TIM3
TIM_Cmd(TIM3, ENABLE);
while(1)
{
// 发送10us的高电平脉冲
GPIO_SetBits(GPIOB, TRIG);
delay_us(10);
GPIO_ResetBits(GPIOB, TRIG);
// 等待ECHO引脚变高电平
while(GPIO_ReadInputDataBit(GPIOB, ECHO) == RESET);
// 启动计数器
TIM_SetCounter(TIM3, 0);
TIM_ITConfig(TIM3, TIM_IT_CC1, ENABLE);
// 等待ECHO引脚变低电平
while(GPIO_ReadInputDataBit(GPIOB, ECHO) == SET);
// 关闭计数器
TIM_ITConfig(TIM3, TIM_IT_CC1, DISABLE);
distance = (float)TIM_GetCapture1(TIM3) / 58.0;
sprintf(str, "Distance: %.2f cm\n", distance);
printf(str);
delay_ms(1000);
}
}
void TIM3_IRQHandler(void)
{
if(TIM_GetITStatus(TIM3, TIM_IT_CC1) != RESET)
{
TIM_ClearITPendingBit(TIM3, TIM_IT_CC1);
}
}
void delay_us(u32 us)
{
SysTick_Config(SystemCoreClock / 1000000);
while(us--)
{
while(!(SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk));
}
SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;
}
void delay_ms(u16 ms)
{
SysTick_Config(SystemCoreClock / 1000);
while(ms--)
{
while(!(SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk));
}
SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;
}
```
这段代码会通过超声波测距模块hc-sr04测量距离,并将距离通过串口输出到PC端。同时,还使用了定时器TIM3来计时。
阅读全文