探索者Arduino模拟红外避障小车代码
时间: 2023-07-09 14:30:26 浏览: 78
好的,以下是一个简单的探索者Arduino模拟红外避障小车代码:
```
#include <AFMotor.h> //导入电机驱动库
AF_DCMotor motor1(1); //定义电机1
AF_DCMotor motor2(2); //定义电机2
int irLeft = 7; //定义左红外传感器引脚
int irRight = 6; //定义右红外传感器引脚
void setup() {
pinMode(irLeft, INPUT); //初始化左红外传感器
pinMode(irRight, INPUT); //初始化右红外传感器
Serial.begin(9600); //初始化串口通信(可选)
}
void loop() {
int leftDist = analogRead(irLeft); //读取左红外传感器的数值
int rightDist = analogRead(irRight); //读取右红外传感器的数值
if (leftDist > 600 && rightDist > 600) { //如果左右传感器都检测不到障碍物
motor1.setSpeed(200); //电机1前进
motor1.run(FORWARD);
motor2.setSpeed(200); //电机2前进
motor2.run(FORWARD);
} else if (leftDist < 600 && rightDist > 600) { //如果左边检测到障碍物
motor1.setSpeed(0); //电机1停止
motor1.run(RELEASE);
motor2.setSpeed(200); //电机2后退
motor2.run(BACKWARD);
} else if (leftDist > 600 && rightDist < 600) { //如果右边检测到障碍物
motor1.setSpeed(200); //电机1后退
motor1.run(BACKWARD);
motor2.setSpeed(0); //电机2停止
motor2.run(RELEASE);
} else { //如果左右传感器都检测到障碍物
motor1.setSpeed(0); //电机1停止
motor1.run(RELEASE);
motor2.setSpeed(0); //电机2停止
motor2.run(RELEASE);
}
}
```
这个代码利用了Arduino的模拟输入功能,读取红外传感器的数值,根据检测到的障碍物位置来控制小车的行驶方向。你可以根据自己的需要进行修改和优化。