使用stm32f103c8t6和keil5编写超声波代码
时间: 2023-05-17 08:05:36 浏览: 138
基于STM32F103C8T6超声波测距源码及接线(已调),stm32超声波测距代码,C,C++
5星 · 资源好评率100%
非常感谢您的提问。以下是使用stm32f103c8t6和keil5编写超声波代码的示例:
#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 = 71;
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_SetBits(TRIG_PORT, TRIG_PIN);
delay_us(10);
GPIO_ResetBits(TRIG_PORT, TRIG_PIN);
while(GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) == RESET);
TIM_SetCounter(TIM2, 0);
while(GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) == SET);
start = TIM_GetCounter(TIM2);
while(GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) == RESET);
end = TIM_GetCounter(TIM2);
distance = (float)(end - start) / 58.0;
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);
}
}
希望这个示例能够帮助到您。如果您有任何问题,请随时问我。
阅读全文