I have a HC-SR04 sensor mounted on a stepper motor, mounted on a car. The idea is this:
- The car moves forward with the ultrasonic sensor facing the front
- If the sensor reads a small distance the car do the following:
- Stop
- Turn the sensor to the left and get a new distance
- Turn the sensor to the Right and get a new distance
- Drive slightly backward
- The car turns the to direction the distance was the highest
- Drive forward again
I think I must have wrongly understood how the echo/ultrasonic sensor works. Because when I read values to the left and right, it will always return zero, but reading values when driving forward works very well.
Below is the relevant code
//Trigger
void triggerEcho(){
digitalWrite(echoTrigPin,LOW);
delayMicroseconds(5);
digitalWrite(echoTrigPin,HIGH);
delayMicroseconds(10);
digitalWrite(echoTrigPin,LOW);
}
//Trigger, receive and calculate distance (cm)
long getEchoDistance(){
triggerEcho();
pinMode(echoRecPin, INPUT);
long echoDuration = pulseIn(echoRecPin, HIGH);
return echoDuration / 58;
}
void loop(){
long distance = getEchoDistance();
//If front obstacle is encountered
if((distance < 5) && (distance != 0)){
carStop();
servo.write(180); //turn echo sensor left
delay(250);
long distanceL = getEchoDistance(); //trigger and read sensor value
servo.write(0); //turn echo sensor right
delay(250);
long distanceR = getEchoDistance(); //trigger and read sensor value
//this will always show distance as 0
Serial.print(" LEFT :"); Serial.print(distanceL); Serial.print("\n");
Serial.print(" RIGHT:"); Serial.print(distanceR); Serial.print("\n");
carDriveBackward(135, 1.185, 1.0); //drive backwards
delay(250);
if(distanceR>distanceL) //turn in the direction that was furthest
carTurnRight(100,1250);
else
carTurnLeft(100,1250);
carStop();
servo.write(90); //face sensor forward
delay(250);
}
else
carDriveForward(135, 1.185, 1.0); //R - L
}
I bet something is wrong with how I'm implementing the triggerEcho()
and getEchoDistance()
. I excluded anything on the wiring and pins, as the reading of the distance is very correct when reading the facing the front.