我正在为具有障碍物和边缘避免机制的无线遥控机器人编写代码。因此,这里我们用移动设备控制机器人,现在如果障碍物在它前面或它即将从高处掉落,它将避开它。为了避开障碍物,我使用了HC-05超声波传感器。但是我得到的距离是超声波传感器零。为什么? `
#include<Servo.h>
Servo myservo;
const int trigPin = 2;
const int echoPin = 4;
String voice;
long duration;
int distance;
int
M11 = 13,
M12 = 12,
M21 = 11,
M22 = 10;
void stay(){
digitalWrite(M11, LOW);
digitalWrite(M12, LOW);
digitalWrite(M21, LOW);
digitalWrite(M22, LOW);
}
void forward() {
digitalWrite(M11, HIGH);
digitalWrite(M12, LOW);
digitalWrite(M21, HIGH);
digitalWrite(M22, LOW);
}
void backward(){
digitalWrite(M11, LOW);
digitalWrite(M12, HIGH);
digitalWrite(M21, LOW);
digitalWrite(M22, HIGH);
}
void left(){
digitalWrite(M11, LOW);
digitalWrite(M12, LOW);
digitalWrite(M21, HIGH);
digitalWrite(M22, LOW);
delay(1000);
digitalWrite(M11,HIGH);
}
void right(){
digitalWrite(M11, HIGH);
digitalWrite(M12, LOW);
digitalWrite(M21, LOW);
digitalWrite(M22, LOW);
delay(1000);
digitalWrite(M21,HIGH);
}
int dist()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
Serial.println(distance);
return distance;
}
void Avoid(int d)
{
int d1,d2;
if(d<18 || (digitalRead( 9)==1) || (digitalRead( 8)==0))
{
stay();
delay(500);
backward();
delay(650);
stay();
myservo.write(25);
d1=dist();
delay(650);
myservo.write(90);
delay(500);
myservo.write(180);
d2=dist();
delay(650);
myservo.write(140);
if(d1>d2)
{
left();
delay(800);
}
else
{
right();
delay(800);
}
}
}
void setup() {
Serial.begin(9600);
myservo.attach(7);
pinMode(8,INPUT);
pinMode(9,INPUT);
pinMode(M11, OUTPUT);
pinMode(M12, OUTPUT);
pinMode(M21, OUTPUT);
pinMode(M22, OUTPUT);
}
void loop() {
int d,d1,d2;
d=dist();
Serial.println("D:");
Serial.println(d);
myservo.write(140);
while (Serial.available())
{ //Check if there is an available byte to
read
delay(10); //Delay added to make thing stable
char c = Serial.read();
if (c == '#') {break;}
voice += c;
}
if (voice.length() > 0) {
Serial.println(voice);
if(voice == "forward") {forward();} //Move Robot Forward (Call
Function)
else if(voice == "backward"){backward();} //Move Robot Backward
(Call Function)
else if(voice == "left"){left();} //Move Robot Left (Call
Function)
else if(voice == "right"){right();} //Move Robot right (Call
Function)
else if(voice == "stop"){stay();} //Stop Robot (Call Function)
voice="";
}
Avoid(d);
}