STM32配置HC-SR04的代码,要求用串口输出结果。
时间: 2024-05-20 10:15:47 浏览: 78
基于STM32的倒车雷达项目-OLED显示,HC-SR04+源代码+文档说明
您好!感谢您的提问。以下是包含HC-SR04的STM32的基本代码,其中使用串口输出结果:
#include "stm32f10x.h"
#include <stdio.h>
#define TRIG_PIN GPIO_Pin_0
#define ECHO_PIN GPIO_Pin_1
#define TRIG_PORT GPIOA
#define ECHO_PORT GPIOA
void delay_us(uint32_t us) {
us *= 100;
while (us--) {
__NOP();
}
}
float measure_distance() {
float distance;
uint32_t pulse_width;
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) != SET)
;
uint32_t start_time = TIM_GetCounter(TIM2);
while (GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) != RESET)
;
pulse_width = TIM_GetCounter(TIM2) - start_time;
distance = pulse_width * 0.017;
return distance;
}
int main() {
// Initialize system
SystemInit();
// Enable clocks
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
// Initialize GPIOs
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_StructInit(&GPIO_InitStructure);
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_IPU;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(ECHO_PORT, &GPIO_InitStructure);
// Initialize timer
TIM_TimeBaseInitTypeDef TIM_InitStructure;
TIM_StructInit(&TIM_InitStructure);
TIM_InitStructure.TIM_Prescaler = SystemCoreClock / 1000000;
TIM_InitStructure.TIM_Period = 0xFFFFFFFF;
TIM_TimeBaseInit(TIM2, &TIM_InitStructure);
// Initialize USART
USART_InitTypeDef USART_InitStructure;
USART_StructInit(&USART_InitStructure);
USART_InitStructure.USART_BaudRate = 115200;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl =
USART_HardwareFlowControl_None;
USART_Init(USART1, &USART_InitStructure);
// Enable USART
USART_Cmd(USART1, ENABLE);
while (1) {
float distance = measure_distance();
char buffer[50];
sprintf(buffer, "Distance: %f cm\n", distance);
printf(buffer);
}
}
希望这可以帮助到您!
阅读全文