keil5写stm32f103c8t6使用超声波的代码
时间: 2023-05-17 14:05:24 浏览: 105
非常感谢您的提问。以下是使用Keil5编写STM32F103C8T6超声波代码的示例:
#include "stm32f10x.h"
#include "delay.h"
#include "usart.h"
#define TRIG_PIN GPIO_Pin_0
#define ECHO_PIN GPIO_Pin_1
#define TRIG_PORT GPIOA
#define ECHO_PORT GPIOA
void TIM2_Init(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
TIM_TimeBaseStructure.TIM_Prescaler = 72 - 1;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
TIM_Cmd(TIM2, ENABLE);
}
void Ultrasonic_Init(void)
{
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);
}
float Ultrasonic_GetDistance(void)
{
uint32_t start, end;
float distance;
GPIO_ResetBits(TRIG_PORT, TRIG_PIN);
delay_us(2);
GPIO_SetBits(TRIG_PORT, TRIG_PIN);
delay_us(10);
GPIO_ResetBits(TRIG_PORT, TRIG_PIN);
while (GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) == RESET);
start = TIM_GetCounter(TIM2);
while (GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) != RESET);
end = TIM_GetCounter(TIM2);
distance = (float)(end - start) * 0.017;
return distance;
}
int main(void)
{
float distance;
SystemInit();
delay_init();
USART1_Init();
Ultrasonic_Init();
TIM2_Init();
while (1)
{
distance = Ultrasonic_GetDistance();
printf("Distance: %.2f cm\r\n", distance);
delay_ms(500);
}
}
希望这可以帮助您!
阅读全文