stm32超声波测速c代码
时间: 2024-01-04 15:18:50 浏览: 82
stm32超声波代码
以下是使用HC-SR04超声波传感器,对两路超声波传感器STM32F103ZET6的正点原子的精英版进行控制,实现两路超声波传感器分别测量物体的距离,测量物体移动的速度,并将测量的速度和距离显示在LCD的屏幕上,同时在串口输出的STM32超声波测速C代码:
```c
#include "sys.h"
#include "delay.h"
#include "usart.h"
#include "led.h"
#include "lcd.h"
#include "hc_sr04.h"
#include "timer.h"
#include "exti.h"
#include "math.h"
#define PI 3.1415926
u32 time1 = 0, time2 = 0;
u32 distance1 = 0, distance2 = 0;
u32 speed1 = 0, speed2 = 0;
u32 last_distance1 = 0, last_distance2 = 0;
u32 last_time1 = 0, last_time2 = 0;
u32 current_time = 0;
float speed = 0;
float distance = 0;
int main(void)
{
u8 t = 0;
u8 dis1[16], dis2[16], spd1[16], spd2[16];
u8 dis[16], spd[16];
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
delay_init(72);
uart_init(115200);
LED_Init();
TIM3_Int_Init(999, 71);
HC_SR04_Init();
LCD_Init();
while (1)
{
time1 = HC_SR04_Get_Time(1);
time2 = HC_SR04_Get_Time(2);
distance1 = time1 * 17 / 1000;
distance2 = time2 * 17 / 1000;
speed1 = abs(distance1 - last_distance1) / (time1 - last_time1);
speed2 = abs(distance2 - last_distance2) / (time2 - last_time2);
last_distance1 = distance1;
last_distance2 = distance2;
last_time1 = time1;
last_time2 = time2;
sprintf(dis1, "dis1:%dcm", distance1);
sprintf(dis2, "dis2:%dcm", distance2);
sprintf(spd1, "spd1:%dcm/s", speed1);
sprintf(spd2, "spd2:%dcm/s", speed2);
LCD_ShowString(0, 0, dis1);
LCD_ShowString(0, 1, dis2);
LCD_ShowString(0, 2, spd1);
LCD_ShowString(0, 3, spd2);
current_time = TIM3->CNT;
if (current_time < time1 && current_time < time2)
{
distance = (time2 - time1) * 17 / 2000.0;
speed = abs(distance - last_distance1) / ((time2 - time1) / 1000000.0);
sprintf(dis, "dis:%.2fcm", distance);
sprintf(spd, "spd:%.2fcm/s", speed);
LCD_ShowString(0, 4, dis);
LCD_ShowString(0, 5, spd);
printf("distance:%.2fcm, speed:%.2fcm/s\r\n", distance, speed);
}
delay_ms(100);
}
}
void TIM3_IRQHandler(void)
{
if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
TIM_SetCounter(TIM3, 0);
}
}
```
阅读全文