基于stm32的智能循迹避障小车,三路红外循迹,超声波避障,在循迹时遇到障碍物能够绕开障碍物后能回到原来的轨道上继续循迹的c语言代码
时间: 2023-12-30 22:03:42 浏览: 198
好的,以下是一个基于STM32的智能循迹避障小车的C语言代码,实现了三路红外循迹和超声波避障功能。当小车在循迹时遇到障碍物时,会绕开障碍物并回到原来的轨道上继续循迹。
```c
#include "stm32f10x.h"
#include "delay.h"
#include "usart.h"
#include "motor.h"
#include "infrared.h"
#include "ultrasonic.h"
int main(void)
{
uint8_t infrared_state = 0x00;
uint8_t last_infrared_state = 0x00;
uint16_t ultrasonic_distance = 0;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
Delay_Init();
USART_Config();
Motor_Config();
Infrared_Config();
Ultrasonic_Config();
while (1)
{
infrared_state = Infrared_ReadState();
ultrasonic_distance = Ultrasonic_ReadDistance();
if (ultrasonic_distance > 0 && ultrasonic_distance < 20) // 遇到障碍物
{
Motor_Stop();
Delay_ms(500);
Motor_Left(90);
Delay_ms(1000);
while (Infrared_ReadState() != last_infrared_state)
{
Motor_Forward(50);
Delay_ms(50);
}
Motor_Right(90);
Delay_ms(1000);
while (Infrared_ReadState() != last_infrared_state)
{
Motor_Forward(50);
Delay_ms(50);
}
Motor_Left(90);
Delay_ms(1000);
while (Infrared_ReadState() != last_infrared_state)
{
Motor_Forward(50);
Delay_ms(50);
}
Motor_Right(90);
Delay_ms(1000);
Motor_Forward(50);
Delay_ms(500);
}
else // 正常循迹
{
last_infrared_state = infrared_state;
if (infrared_state == 0x01)
{
Motor_Left(50);
}
else if (infrared_state == 0x04)
{
Motor_Right(50);
}
else
{
Motor_Forward(50);
}
}
}
}
```
在上面的代码中,`Infrared_ReadState()`函数用于读取红外传感器的状态,`Ultrasonic_ReadDistance()`函数用于读取超声波传感器的距离。当超声波传感器探测到障碍物时,小车会停止并向左转,然后根据红外传感器的输出绕开障碍物并回到原来的轨道上继续循迹。如果没有遇到障碍物,则根据红外传感器的输出进行循迹运动。
阅读全文