arduino寻迹小车l289n代码
时间: 2023-11-18 19:04:41 浏览: 130
是一个基于L289N电机驱动芯片的Arduino寻迹小车代码示例:
```arduino
//定义引脚
int left_motor_1 = 2;
int left_motor_2 = 3;
int right_motor_1 = 4;
int right_motor_2 = 5;
int left_sensor_1 = A0;
int left_sensor_2 = A1;
int right_sensor_1 = A2;
int right_sensor_2 = A3;
void setup() {
//设置引脚模式
pinMode(left_motor_1, OUTPUT);
pinMode(left_motor_2, OUTPUT);
pinMode(right_motor_1, OUTPUT);
pinMode(right_motor_2, OUTPUT);
pinMode(left_sensor_1, INPUT);
pinMode(left_sensor_2, INPUT);
pinMode(right_sensor_1, INPUT);
pinMode(right_sensor_2, INPUT);
}
void loop() {
//读取传感器数值
int left_1 = analogRead(left_sensor_1);
int left_2 = analogRead(left_sensor_2);
int right_1 = analogRead(right_sensor_1);
int right_2 = analogRead(right_sensor_2);
//判断传感器数值,控制小车运动
if (left_1 < 500 && left_2 < 500) {
digitalWrite(left_motor_1, HIGH);
digitalWrite(left_motor_2, LOW);
digitalWrite(right_motor_1, LOW);
digitalWrite(right_motor_2, HIGH);
} else if (right_1 < 500 && right_2 < 500) {
digitalWrite(left_motor_1, LOW);
digitalWrite(left_motor_2, HIGH);
digitalWrite(right_motor_1, HIGH);
digitalWrite(right_motor_2, LOW);
} else {
digitalWrite(left_motor_1, HIGH);
digitalWrite(left_motor_2, LOW);
digitalWrite(right_motor_1, HIGH);
digitalWrite(right_motor_2, LOW);
}
}
```
该代码使用了4个红外传感器来实现小车的巡线功能,当左侧或右侧的传感器检测到黑色线条时,小车会向相反的方向转向,以保持在线条上行驶。当所有传感器都检测不到线条时,小车会直行。
阅读全文