给我写一个用stm32的hcsr04超声波模块测距代码
时间: 2024-04-03 22:12:25 浏览: 64
STM32超声波测距代码-HC-SR04.zip
4星 · 用户满意度95%
好的,以下是一个简单的使用STM32的HC-SR04超声波模块测距的代码,仅供参考:
```
#include "stm32f10x.h"
#include <stdio.h>
#include <stdbool.h>
#define TRIG_PIN GPIO_Pin_0
#define ECHO_PIN GPIO_Pin_1
volatile uint32_t pulse_start_time = 0;
volatile uint32_t pulse_end_time = 0;
volatile bool is_pulse_started = false;
volatile bool is_pulse_ended = false;
void delay(uint32_t ms) {
while (ms--) {
for (volatile int i = 0; i < 2000; i++);
}
}
void init_gpio() {
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitTypeDef gpio_init;
gpio_init.GPIO_Pin = TRIG_PIN;
gpio_init.GPIO_Mode = GPIO_Mode_Out_PP;
gpio_init.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &gpio_init);
gpio_init.GPIO_Pin = ECHO_PIN;
gpio_init.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &gpio_init);
}
void init_timer() {
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseInitTypeDef tim_init;
tim_init.TIM_Period = 0xFFFF;
tim_init.TIM_Prescaler = 71;
tim_init.TIM_ClockDivision = TIM_CKD_DIV1;
tim_init.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &tim_init);
TIM_Cmd(TIM2, ENABLE);
}
void init_interrupt() {
NVIC_InitTypeDef nvic_init;
nvic_init.NVIC_IRQChannel = TIM2_IRQn;
nvic_init.NVIC_IRQChannelPreemptionPriority = 0;
nvic_init.NVIC_IRQChannelSubPriority = 0;
nvic_init.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&nvic_init);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
}
void send_pulse() {
GPIO_SetBits(GPIOA, TRIG_PIN);
delay(10);
GPIO_ResetBits(GPIOA, TRIG_PIN);
}
float get_distance() {
send_pulse();
while (!is_pulse_ended);
float time_elapsed = (pulse_end_time - pulse_start_time) / 1000000.0;
float distance = time_elapsed * 340.0 / 2.0;
is_pulse_ended = false;
return distance;
}
int main() {
init_gpio();
init_timer();
init_interrupt();
while (true) {
float distance = get_distance();
printf("Distance: %.2f cm\n", distance);
delay(1000);
}
}
void TIM2_IRQHandler() {
if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET) {
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
if (!is_pulse_started) {
pulse_start_time = TIM_GetCounter(TIM2);
is_pulse_started = true;
}
else {
pulse_end_time = TIM_GetCounter(TIM2);
is_pulse_ended = true;
is_pulse_started = false;
}
}
}
```
这个代码使用了STM32的定时器TIM2来计时超声波的回响时间,通过测量回响时间来计算距离。其中,TRIG_PIN为超声波模块的触发引脚,ECHO_PIN为超声波模块的回响引脚。在main函数中不断调用get_distance函数来获取距离,并通过printf函数输出到串口上。在定时器中断中,记录下超声波触发和回响的时间戳,方便后续计算距离。
阅读全文