Arduino用UNO板为底座的寻迹小车代码
时间: 2024-06-20 17:03:16 浏览: 186
你好,以下是一个使用Arduino UNO板的寻迹小车的代码示例:
```
//定义左右电机引脚
int motorLeftForward = 5;
int motorLeftBackward = 6;
int motorRightForward = 10;
int motorRightBackward = 9;
//定义寻迹模块引脚
int leftSensor = A0;
int middleSensor = A1;
int rightSensor = A2;
void setup() {
//初始化电机引脚为输出模式
pinMode(motorLeftForward, OUTPUT);
pinMode(motorLeftBackward, OUTPUT);
pinMode(motorRightForward, OUTPUT);
pinMode(motorRightBackward, OUTPUT);
//初始化寻迹模块引脚为输入模式
pinMode(leftSensor, INPUT);
pinMode(middleSensor, INPUT);
pinMode(rightSensor, INPUT);
}
void loop() {
//读取寻迹模块的数据
int leftValue = digitalRead(leftSensor);
int middleValue = digitalRead(middleSensor);
int rightValue = digitalRead(rightSensor);
//当三个传感器都在黑线上时,小车直行
if (leftValue == LOW && middleValue == LOW && rightValue == LOW) {
digitalWrite(motorLeftForward, HIGH);
digitalWrite(motorLeftBackward, LOW);
digitalWrite(motorRightForward, HIGH);
digitalWrite(motorRightBackward, LOW);
}
//当中间传感器在黑线上时,小车向前直行
else if (middleValue == LOW) {
digitalWrite(motorLeftForward, HIGH);
digitalWrite(motorLeftBackward, LOW);
digitalWrite(motorRightForward, HIGH);
digitalWrite(motorRightBackward, LOW);
}
//当左边传感器在黑线上时,小车向左转弯
else if (leftValue == LOW) {
digitalWrite(motorLeftForward, LOW);
digitalWrite(motorLeftBackward, HIGH);
digitalWrite(motorRightForward, HIGH);
digitalWrite(motorRightBackward, LOW);
}
//当右边传感器在黑线上时,小车向右转弯
else if (rightValue == LOW) {
digitalWrite(motorLeftForward, HIGH);
digitalWrite(motorLeftBackward, LOW);
digitalWrite(motorRightForward, LOW);
digitalWrite(motorRightBackward, HIGH);
}
}
```
这是一个简单的代码示例,实现了当寻迹模块检测到黑线时,小车会向对应的方向转弯。你可以根据自己的需要修改代码以实现更复杂的功能。
阅读全文