能写keil5中超声波测距示例代码吗
时间: 2023-04-10 21:03:07 浏览: 102
当然可以,以下是示例代码:
#include "stm32f4xx.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_rcc.h"
#include "stm32f4xx_tim.h"
#define TRIG_PIN GPIO_Pin_0
#define ECHO_PIN GPIO_Pin_1
#define TRIG_PORT GPIOA
#define ECHO_PORT GPIOA
#define TIMx TIM2
void delay_us(uint32_t us)
{
uint32_t ticks;
ticks = us * (SystemCoreClock / 1000000);
while(ticks--);
}
void TIM_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructure.TIM_Period = 0xFFFFFFFF;
TIM_TimeBaseStructure.TIM_Prescaler = 84 - 1;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIMx, &TIM_TimeBaseStructure);
TIM_Cmd(TIMx, ENABLE);
}
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = TRIG_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(TRIG_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = ECHO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(ECHO_PORT, &GPIO_InitStructure);
}
float get_distance(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(TIMx);
while(GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) == SET);
end_time = TIM_GetCounter(TIMx);
distance = (float)(end_time - start_time) * 0.034 / 2;
return distance;
}
int main(void)
{
float distance;
GPIO_Configuration();
TIM_Configuration();
while(1)
{
distance = get_distance();
printf("Distance: %.2f cm\n", distance);
delay_us(100000);
}
}
阅读全文