用arduino写一个循迹小车的程序
时间: 2023-05-21 15:00:50 浏览: 114
好的,以下是一个简单的用Arduino编写的循迹小车程序:
```
int leftPin = 2; // 左侧传感器引脚
int rightPin = 3; // 右侧传感器引脚
int leftMotorPin = 5; // 左侧电机引脚
int rightMotorPin = 6; // 右侧电机引脚
void setup() {
pinMode(leftPin, INPUT);
pinMode(rightPin, INPUT);
pinMode(leftMotorPin, OUTPUT);
pinMode(rightMotorPin, OUTPUT);
}
void loop() {
int leftSensor = digitalRead(leftPin);
int rightSensor = digitalRead(rightPin);
if (leftSensor == HIGH && rightSensor == HIGH) { // 直行
digitalWrite(leftMotorPin, HIGH);
digitalWrite(rightMotorPin, HIGH);
} else if (leftSensor == LOW && rightSensor == HIGH) { // 左转
digitalWrite(leftMotorPin, LOW);
digitalWrite(rightMotorPin, HIGH);
} else if (leftSensor == HIGH && rightSensor == LOW) { // 右转
digitalWrite(leftMotorPin, HIGH);
digitalWrite(rightMotorPin, LOW);
} else { // 停止
digitalWrite(leftMotorPin, LOW);
digitalWrite(rightMotorPin, LOW);
}
}
```
这个程序使用两个红外线传感器来检测循迹小车的位置,根据传感器的读数来控制左右电机的转动,从而实现循迹小车的运动。
阅读全文