循迹小车代码
时间: 2023-07-09 12:21:02 浏览: 135
以下是一个简单的循迹小车代码,使用Arduino Uno和红外线传感器实现:
```c++
int leftMotor1 = 5;
int leftMotor2 = 6;
int rightMotor1 = 9;
int rightMotor2 = 10;
int leftSensor = A0;
int rightSensor = A1;
void setup() {
pinMode(leftMotor1, OUTPUT);
pinMode(leftMotor2, OUTPUT);
pinMode(rightMotor1, OUTPUT);
pinMode(rightMotor2, OUTPUT);
}
void loop() {
int leftReading = analogRead(leftSensor);
int rightReading = analogRead(rightSensor);
if (leftReading < 500 && rightReading < 500) {
// Both sensors off the line, stop
digitalWrite(leftMotor1, LOW);
digitalWrite(leftMotor2, LOW);
digitalWrite(rightMotor1, LOW);
digitalWrite(rightMotor2, LOW);
} else if (leftReading < 500) {
// Left sensor off the line, turn right
digitalWrite(leftMotor1, HIGH);
digitalWrite(leftMotor2, LOW);
digitalWrite(rightMotor1, LOW);
digitalWrite(rightMotor2, HIGH);
} else if (rightReading < 500) {
// Right sensor off the line, turn left
digitalWrite(leftMotor1, LOW);
digitalWrite(leftMotor2, HIGH);
digitalWrite(rightMotor1, HIGH);
digitalWrite(rightMotor2, LOW);
} else {
// Both sensors on the line, go straight
digitalWrite(leftMotor1, HIGH);
digitalWrite(leftMotor2, LOW);
digitalWrite(rightMotor1, HIGH);
digitalWrite(rightMotor2, LOW);
}
}
```
该代码使用两个红外线传感器检测小车是否在黑线上,如果左边的传感器检测到黑线,小车就会向左转,如果右边的传感器检测到黑线,小车就会向右转,如果两个传感器都检测到黑线,小车就会直线前进。
阅读全文