arduino nano 小车,三个循迹,全代码
时间: 2024-12-19 19:08:30 浏览: 26
好的,以下是一个基于Arduino Nano的小车循迹代码示例。这个示例使用了三个循迹传感器来控制小车的运动。
### 硬件连接
- 左循迹传感器连接到A0
- 中循迹传感器连接到A1
- 右循迹传感器连接到A2
- 左电机控制引脚连接到D5和D6
- 右电机控制引脚连接到D9和D10
### 代码示例
```cpp
// 定义循迹传感器引脚
const int leftSensorPin = A0;
const int middleSensorPin = A1;
const int rightSensorPin = A2;
// 定义电机控制引脚
const int leftMotorForward = 5;
const int leftMotorBackward = 6;
const int rightMotorForward = 9;
const int rightMotorBackward = 10;
void setup() {
// 初始化串口通信
Serial.begin(9600);
// 初始化传感器引脚
pinMode(leftSensorPin, INPUT);
pinMode(middleSensorPin, INPUT);
pinMode(rightSensorPin, INPUT);
// 初始化电机控制引脚
pinMode(leftMotorForward, OUTPUT);
pinMode(leftMotorBackward, OUTPUT);
pinMode(rightMotorForward, OUTPUT);
pinMode(rightMotorBackward, OUTPUT);
}
void loop() {
// 读取传感器值
int leftSensorValue = digitalRead(leftSensorPin);
int middleSensorValue = digitalRead(middleSensorPin);
int rightSensorValue = digitalRead(rightSensorPin);
// 打印传感器值到串口监视器
Serial.print("Left Sensor: ");
Serial.print(leftSensorValue);
Serial.print(" Middle Sensor: ");
Serial.print(middleSensorValue);
Serial.print(" Right Sensor: ");
Serial.println(rightSensorValue);
// 根据传感器值控制电机
if (middleSensorValue == LOW) {
// 中间传感器检测到黑线,直行
moveForward();
} else if (leftSensorValue == LOW) {
// 左边传感器检测到黑线,向左转
turnLeft();
} else if (rightSensorValue == LOW) {
// 右边传感器检测到黑线,向右转
turnRight();
} else {
// 没有检测到黑线,停止
stopMoving();
}
}
void moveForward() {
digitalWrite(leftMotorForward, HIGH);
digitalWrite(leftMotorBackward, LOW);
digitalWrite(rightMotorForward, HIGH);
digitalWrite(rightMotorBackward, LOW);
}
void turnLeft() {
digitalWrite(leftMotorForward, LOW);
digitalWrite(leftMotorBackward, LOW);
digitalWrite(rightMotorForward, HIGH);
digitalWrite(rightMotorBackward, LOW);
}
void turnRight() {
digitalWrite(leftMotorForward, HIGH);
digitalWrite(leftMotorBackward, LOW);
digitalWrite(rightMotorForward, LOW);
digitalWrite(rightMotorBackward, LOW);
}
void stopMoving() {
digitalWrite(leftMotorForward, LOW);
digitalWrite(leftMotorBackward, LOW);
digitalWrite(rightMotorForward, LOW);
digitalWrite(rightMotorBackward, LOW);
}
```
### 代码说明
1. **初始化部分**:在`setup()`函数中,初始化串口通信和所有引脚的模式。
2. **主循环部分**:在`loop()`函数中,读取三个循迹传感器的值,并根据传感器的状态控制电机的运动。
3. **电机控制函数**:定义了四个函数`moveForward()`、`turnLeft()`、`turnRight()`和`stopMoving()`,分别用于控制小车前进、左转、右转和停止。
希望这个示例对你有所帮助!
阅读全文