arduino寻迹小车红外对管代码
时间: 2023-12-20 19:30:36 浏览: 127
以下是Arduino寻迹小车红外对管的代码示例:
```arduino
//定义左右电机引脚
int leftMotor1 = 5;
int leftMotor2 = 6;
int rightMotor1 = 10;
int rightMotor2 = 9;
//定义左右红外对管引脚
int leftSensor = A0;
int rightSensor = A1;
void setup() {
//初始化电机引脚
pinMode(leftMotor1, OUTPUT);
pinMode(leftMotor2, OUTPUT);
pinMode(rightMotor1, OUTPUT);
pinMode(rightMotor2, OUTPUT);
}
void loop() {
//读取左右红外对管的值
int leftValue = analogRead(leftSensor);
int rightValue = analogRead(rightSensor);
//判断左右红外对管是否在黑线上
if (leftValue < 500 && rightValue < 500) {
//左右都在黑线上,直走
digitalWrite(leftMotor1, HIGH);
digitalWrite(leftMotor2, LOW);
digitalWrite(rightMotor1, HIGH);
digitalWrite(rightMotor2, LOW);
} else if (leftValue < 500 && rightValue > 500) {
//左边在黑线上,右边不在,左转
digitalWrite(leftMotor1, LOW);
digitalWrite(leftMotor2, HIGH);
digitalWrite(rightMotor1, HIGH);
digitalWrite(rightMotor2, LOW);
} else if (leftValue > 500 && rightValue < 500) {
//右边在黑线上,左边不在,右转
digitalWrite(leftMotor1, HIGH);
digitalWrite(leftMotor2, LOW);
digitalWrite(rightMotor1, LOW);
digitalWrite(rightMotor2, HIGH);
} else {
//左右都不在黑线上,停止
digitalWrite(leftMotor1, LOW);
digitalWrite(leftMotor2, LOW);
digitalWrite(rightMotor1, LOW);
digitalWrite(rightMotor2, LOW);
}
}
```
阅读全文