Hello I am trying to control two DC motors using the HC-SR04 ultrasonic sensor. I am using Arduino uno and the Motor control shield. Bellow is my code. The motor only go forward. What am I doing wrong?
#include <AFMotor.h>
AF_DCMotor motor1(1,MOTOR12_2KHZ);
AF_DCMotor motor2(2,MOTOR12_2KHZ);
//AF_DCMotor motor3(3);
//AF_DCMotor motor4(4);
const int trigPin=9;
const int echoPin=10;
//int status=0; //0-off 1-forward 2-back
void setup()
{Serial.begin(9600);
motor1.setSpeed(200);
motor2.setSpeed(200);
}
void loop()
{
// and the distance result in centimeters
long duration,cm;
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin,LOW);
delayMicroseconds(2);
digitalWrite(trigPin,HIGH);
delayMicroseconds(20);
digitalWrite(trigPin,LOW);
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin,HIGH);
// convert the time into distance
// speed of sound is 340m/s or 29 microseconds per centimeter
cm = microsecondsToCentimeters(duration);
for (cm=0; cm<=100; cm++)
//if (cm<=100)
{
motor1.run(FORWARD); //go forward for cm between 0 and 100
motor2.run(FORWARD);
//println(cm);
delay(100);
}
if (cm<=10){
motor1.run(RELEASE); //Stop
motor2.run(RELEASE);
delay(100); //delay
motor1.run(BACKWARD); //go backward
motor2.run(BACKWARD);
delay(100);
}
else if (cm>10&&cm<12)
{
motor1.run(BACKWARD);// from backward 2cm then turn right
motor2.run(FORWARD);
delay(100);
}
//delay(500);
else if (cm>12&& cm<14)
{
motor1.run(FORWARD); //Left turn
motor2.run(BACKWARD);
delay(100);
//motor1.run(FORWARD); // Left Turn
//motor2.run(BACKWARD);
//delay(500);
}
{
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
}
cm = microsecondsToCentimeters(duration);
}
long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}