arduino避障小车代码
时间: 2023-07-09 09:21:39 浏览: 145
以下是一个简单的Arduino避障小车代码:
```C++
//定义电机引脚
const int leftMotorA = 3;
const int leftMotorB = 5;
const int rightMotorA = 6;
const int rightMotorB = 9;
//定义超声波引脚
const int trigPin = 13;
const int echoPin = 12;
//定义超声波参数
long duration;
int distance;
void setup() {
//设置电机引脚为输出
pinMode(leftMotorA, OUTPUT);
pinMode(leftMotorB, OUTPUT);
pinMode(rightMotorA, OUTPUT);
pinMode(rightMotorB, OUTPUT);
//设置超声波引脚为输入
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
//设置串口通信
Serial.begin(9600);
}
void loop() {
//测量距离
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration/58.2;
//输出距离
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
//根据距离控制小车运动
if(distance > 20) {
forward();
}
else {
backward();
delay(1000);
turnRight();
delay(1000);
}
}
//向前
void forward() {
digitalWrite(leftMotorA, HIGH);
digitalWrite(leftMotorB, LOW);
digitalWrite(rightMotorA, HIGH);
digitalWrite(rightMotorB, LOW);
}
//向后
void backward() {
digitalWrite(leftMotorA, LOW);
digitalWrite(leftMotorB, HIGH);
digitalWrite(rightMotorA, LOW);
digitalWrite(rightMotorB, HIGH);
}
//向左转
void turnLeft() {
digitalWrite(leftMotorA, LOW);
digitalWrite(leftMotorB, HIGH);
digitalWrite(rightMotorA, HIGH);
digitalWrite(rightMotorB, LOW);
}
//向右转
void turnRight() {
digitalWrite(leftMotorA, HIGH);
digitalWrite(leftMotorB, LOW);
digitalWrite(rightMotorA, LOW);
digitalWrite(rightMotorB, HIGH);
}
```
这个代码使用超声波模块测量距离,根据距离控制小车的运动。如果距离大于20厘米,小车向前行驶。如果距离小于等于20厘米,小车后退一秒钟,然后向右转一秒钟。你可以根据具体情况修改距离和转向时间。
阅读全文