Well I keep on trying. In this new variation of the code I introduce the boolean value change ' turnLeft = !turnLeft; ' when there is no obstacle detected. So when an obstacle is detected, the robot rotates in one direction or the other depending on that value.
At this point I think the code is ok to make the robot turn in alternating manner to one side and then when the next obstacle is detected to the other. But instead the robot turns ramdomly to one side or the other.
Variation of the code:
#include <Servo.h>
Servo motorLeft; // Define left motor
Servo motorRight; // Define right motor
#define trigPin A2
#define echoPin A3
boolean turnLeft = true;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
motorLeft.attach(A5); // Set left motor to pin A5
motorRight.attach(A4); // Set right motor to pin A4
}
void loop() {
int duration, distance; //ultrasonic sensor routine
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 30 || distance <= 0){
Serial.println("Out of range");
motorLeft.write(20);
motorRight.write(20);
turnLeft = !turnLeft;
}
if (distance <= 30 && turnLeft == true){
Serial.print(distance);
Serial.println( "cm");
motorLeft.write(170);
motorRight.write(10);
}
if (distance <= 30 && turnLeft == false){
Serial.print(distance);
Serial.println( "cm");
motorLeft.write(10);
motorRight.write(170);
}
}
Getting much closer but not there yet. Help please to get to understand what could still be failing.