2灰度传感器,4电机小车循迹代码
时间: 2023-06-11 09:07:32 浏览: 107
微型寻迹小车、灰度
以下是一个基于Arduino的2灰度传感器、4电机小车循迹代码:
```
//定义引脚
#define rightMotor1 A0
#define rightMotor2 A1
#define leftMotor1 A2
#define leftMotor2 A3
#define rightSensor A4
#define leftSensor A5
//定义变量
int sensorValueL; //左传感器的值
int sensorValueR; //右传感器的值
int threshold = 500; //传感器阈值
int motorSpeed = 255; //电机速度
void setup() {
pinMode(rightMotor1, OUTPUT);
pinMode(rightMotor2, OUTPUT);
pinMode(leftMotor1, OUTPUT);
pinMode(leftMotor2, OUTPUT);
pinMode(rightSensor, INPUT);
pinMode(leftSensor, INPUT);
}
void loop() {
sensorValueL = analogRead(leftSensor);
sensorValueR = analogRead(rightSensor);
//左右传感器都在黑线上时
if (sensorValueL < threshold && sensorValueR < threshold) {
digitalWrite(leftMotor1, HIGH);
digitalWrite(leftMotor2, LOW);
digitalWrite(rightMotor1, HIGH);
digitalWrite(rightMotor2, LOW);
}
//左传感器不在黑线上,右传感器在黑线上时
if (sensorValueL > threshold && sensorValueR < threshold) {
digitalWrite(leftMotor1, LOW);
digitalWrite(leftMotor2, HIGH);
digitalWrite(rightMotor1, HIGH);
digitalWrite(rightMotor2, LOW);
}
//左传感器在黑线上,右传感器不在黑线上时
if (sensorValueL < threshold && sensorValueR > threshold) {
digitalWrite(leftMotor1, HIGH);
digitalWrite(leftMotor2, LOW);
digitalWrite(rightMotor1, LOW);
digitalWrite(rightMotor2, HIGH);
}
//左右传感器都不在黑线上时
if (sensorValueL > threshold && sensorValueR > threshold) {
digitalWrite(leftMotor1, HIGH);
digitalWrite(leftMotor2, LOW);
digitalWrite(rightMotor1, HIGH);
digitalWrite(rightMotor2, LOW);
}
//电机速度
analogWrite(leftMotor1, motorSpeed);
analogWrite(rightMotor1, motorSpeed);
}
```
其中,`rightMotor1`、`rightMotor2`、`leftMotor1`、`leftMotor2`是4个电机控制引脚,`rightSensor`、`leftSensor`是2个灰度传感器引脚。在`loop()`函数中,通过读取传感器的值来判断小车应该往哪个方向前进,并控制电机的转动方向和速度。如果左右传感器都在黑线上,则小车直行;如果左传感器不在黑线上,右传感器在黑线上,则小车右转;如果左传感器在黑线上,右传感器不在黑线上,则小车左转;如果左右传感器都不在黑线上,则小车停止。
阅读全文