arduino循迹小车代码
时间: 2023-09-10 18:05:42 浏览: 202
以下是一个简单的Arduino循迹小车代码,可以用于基本的循迹:
```
int leftMotor1 = 2; //左电机引脚1
int leftMotor2 = 3; //左电机引脚2
int rightMotor1 = 4; //右电机引脚1
int rightMotor2 = 5; //右电机引脚2
int leftSensor = A0; //左传感器引脚
int rightSensor = A1; //右传感器引脚
int threshold = 500; //传感器阈值
void setup() {
pinMode(leftMotor1, OUTPUT);
pinMode(leftMotor2, OUTPUT);
pinMode(rightMotor1, OUTPUT);
pinMode(rightMotor2, OUTPUT);
pinMode(leftSensor, INPUT);
pinMode(rightSensor, INPUT);
}
void loop() {
int leftValue = analogRead(leftSensor); //读取左传感器值
int rightValue = analogRead(rightSensor); //读取右传感器值
if (leftValue > threshold && rightValue > threshold) { //如果两个传感器都在黑线上
digitalWrite(leftMotor1, HIGH); //左电机正转
digitalWrite(leftMotor2, LOW);
digitalWrite(rightMotor1, HIGH); //右电机正转
digitalWrite(rightMotor2, LOW);
}
else if (leftValue > threshold) { //如果左传感器在黑线上
digitalWrite(leftMotor1, LOW); //左电机停止
digitalWrite(leftMotor2, LOW);
digitalWrite(rightMotor1, HIGH); //右电机正转
digitalWrite(rightMotor2, LOW);
}
else if (rightValue > threshold) { //如果右传感器在黑线上
digitalWrite(leftMotor1, HIGH); //左电机正转
digitalWrite(leftMotor2, LOW);
digitalWrite(rightMotor1, LOW); //右电机停止
digitalWrite(rightMotor2, LOW);
}
else { //如果两个传感器都不在黑线上
digitalWrite(leftMotor1, LOW); //左电机停止
digitalWrite(leftMotor2, LOW);
digitalWrite(rightMotor1, LOW); //右电机停止
digitalWrite(rightMotor2, LOW);
}
}
```
该代码使用两个红外线传感器来检测黑线,如果两个传感器都在黑线上,则小车前进;如果左传感器在黑线上,则小车向右转;如果右传感器在黑线上,则小车向左转;如果两个传感器都不在黑线上,则小车停止。您可以根据自己的需要进行修改和调整。
阅读全文