怎么制作arduino雷达避让小车,材料有arduino uno板,超声波传感器,L293D,两个电机,舵机,锂电池,车轮,7805。并帮我写arduino代码。要求能跟前面障碍物保持20cm距离,障碍物前进小车前进,障碍物后退小车后退
时间: 2024-06-19 18:02:07 浏览: 127
制作arduino雷达避让小车需要按照以下步骤进行:
1. 搭建电路:将超声波传感器、L293D、两个电机、舵机、锂电池、车轮、7805等电子元件按照电路图连接起来。
2. 编写arduino代码:将以下代码上传到arduino uno板上,实现小车的自动避障功能。
```
#include <Servo.h>
#define trigPin 2
#define echoPin 3
#define motorPin1 4
#define motorPin2 5
#define motorPin3 6
#define motorPin4 7
int motorSpeed = 200;
Servo myservo;
int pos = 90;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
pinMode(motorPin3, OUTPUT);
pinMode(motorPin4, OUTPUT);
myservo.attach(9);
Serial.begin(9600);
}
void loop() {
int distance = getDistance();
Serial.print("Distance: ");
Serial.println(distance);
if (distance > 20) {
goForward();
} else {
stop();
delay(500);
backOff();
delay(1000);
turnLeft();
delay(1000);
goForward();
}
}
int getDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
int duration = pulseIn(echoPin, HIGH);
int distance = duration * 0.034 / 2;
return distance;
}
void goForward() {
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, HIGH);
digitalWrite(motorPin4, LOW);
}
void stop() {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, LOW);
}
void backOff() {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, HIGH);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, HIGH);
}
void turnLeft() {
myservo.write(pos+45);
}
void turnRight() {
myservo.write(pos-45);
}
```
阅读全文