Arduino UNO 2灰度传感器,4电机小车循迹代码
时间: 2023-06-11 19:07:39 浏览: 177
以下是Arduino UNO使用2个灰度传感器和4个电机的小车循迹代码:
```
//定义引脚
int leftSensor = A0;
int rightSensor = A1;
int leftMotor1 = 6;
int leftMotor2 = 5;
int rightMotor1 = 9;
int rightMotor2 = 10;
//定义阈值
int threshold = 500;
void setup() {
//设置引脚模式
pinMode(leftSensor, INPUT);
pinMode(rightSensor, INPUT);
pinMode(leftMotor1, OUTPUT);
pinMode(leftMotor2, OUTPUT);
pinMode(rightMotor1, OUTPUT);
pinMode(rightMotor2, OUTPUT);
//初始化串口
Serial.begin(9600);
}
void loop() {
//读取传感器值
int leftValue = analogRead(leftSensor);
int rightValue = analogRead(rightSensor);
//输出传感器值
Serial.print("Left Sensor Value: ");
Serial.print(leftValue);
Serial.print(" Right Sensor Value: ");
Serial.println(rightValue);
//判断传感器值是否超过阈值
if (leftValue > threshold && rightValue > threshold) {
//直线行驶
digitalWrite(leftMotor1, HIGH);
digitalWrite(leftMotor2, LOW);
digitalWrite(rightMotor1, HIGH);
digitalWrite(rightMotor2, LOW);
} else if (leftValue > threshold && rightValue < threshold) {
//右转
digitalWrite(leftMotor1, HIGH);
digitalWrite(leftMotor2, LOW);
digitalWrite(rightMotor1, LOW);
digitalWrite(rightMotor2, HIGH);
} else if (leftValue < threshold && rightValue > threshold) {
//左转
digitalWrite(leftMotor1, LOW);
digitalWrite(leftMotor2, HIGH);
digitalWrite(rightMotor1, HIGH);
digitalWrite(rightMotor2, LOW);
} else {
//停车
digitalWrite(leftMotor1, LOW);
digitalWrite(leftMotor2, LOW);
digitalWrite(rightMotor1, LOW);
digitalWrite(rightMotor2, LOW);
}
}
```
注:灰度传感器读取的值在黑线区域较小,在白线区域较大,可以根据实际情况调整阈值。同时,电机的正反转由具体电路实现,这里只是示例代码。
阅读全文