I'm building a robot for a school project. I am currently using an Arduino Uno, two DC motors and an ultrasonic sensor. The two motors are being controlled via the Arduino Motor Shield v3. I want the robot to be autonomous so it has to be able to move around on its own using the ultrasonic sensor.
This is the latest version of my source code:
#include <Servo.h> // include Servo library
#include <AFMotor.h> // include DC motor Library
#define trigPin 12 // define the pins of your sensor
#define echoPin 13
AF_DCMotor motor2(7); // set up motors.
AF_DCMotor motor1(6);
void setup() {
Serial.begin(9600); // begin serial communication
Serial.println("Motor test!");
pinMode(trigPin, OUTPUT); // set the trig pin to output to send sound waves
pinMode(echoPin, INPUT); // set the echo pin to input to receive sound waves
motor1.setSpeed(105); // set the speed of the motors, between 0-255
motor2.setSpeed (105);
}
void loop() {
long duration, distance; // start the scan
digitalWrite(trigPin, LOW);
delayMicroseconds(2); // delays are required for a successful sensor operation.
digitalWrite(trigPin, HIGH);
delayMicroseconds(10); // this delay is required as well!
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1; // convert the distance to centimetres.
// if there's an obstacle ahead at less than 25 centimetres, do the following:
if (distance < 25) {
Serial.println("Close Obstacle detected!" );
Serial.println("Obstacle Details:");
Serial.print("Distance From Robot is " );
Serial.print(distance);
Serial.print(" CM!"); // print out the distance in centimeters.
Serial.println (" The obstacle is declared a threat due to close distance. ");
Serial.println (" Turning !");
motor1.run(FORWARD); // Turn as long as there's an obstacle ahead.
motor2.run (BACKWARD);
} else {
Serial.println("No obstacle detected. going forward");
delay(15);
motor1.run(FORWARD); // if there's no obstacle ahead, Go Forward!
motor2.run(FORWARD);
}
}
The current issue is that the wheels are rotating as expected but after a few turns they stop.
I suspect that the issue is software related, but I am not completely sure. Moreover, I believe that the motors are correctly connected to the motor shield, but I might not handle them properly in the code.
Could anyone please help me solving this issue?