I can't seem to figure out why this code won't work ( I'm a noob). When It runs all it does is activate the drive motor in a continuous loop. I want it to use the ultrasonic sensor then back up and repeat.
void setup() {
pinMode(12, OUTPUT); //drive motor -- HIGH = forwards and LOW = backwards
pinMode(13, OUTPUT); //turn motor -- HIGH = left and LOW = right
//establish motor brake pins
pinMode(9, OUTPUT); //brake (disable) the drive motor
pinMode(8, OUTPUT); //brake (disable) the turn motor
//Turns brake off for drive motor
digitalWrite(9, LOW);
//Turns brake on for turn motor
digitalWrite(8, HIGH);
//Sets initial speed of drive motor
analogWrite(3, 50);
//Sets initial direction of drive motor
digitalWrite(12, HIGH);
pinMode(13,OUTPUT);//sonar trig
pinMode(11,INPUT);//sonar echo
}
void loop()
{
digitalWrite(13, LOW);//clear trig
delayMicroseconds(2);
digitalWrite(13, HIGH);//trig
delayMicroseconds(10);
digitalWrite(13, LOW);//clear trig
long duration = pulseIn(11, HIGH);//read echo
long distance = (duration/2) / 29.1;
if (distance < 30){
//brake drive motor and pause 1/10 second
digitalWrite(9, HIGH);
delay(100);
//
//setting turn motor
//
//turn off brake for turn motor
digitalWrite(8, LOW);
//set turn motor direction
digitalWrite(13, HIGH);
//activate turn motor
analogWrite(11, 255);
//
//setting drive motor
//
//turn off brake of drive motor
digitalWrite(9, LOW);
//set drive motor backwards direction
digitalWrite(12, LOW);
//activate the drive motor
analogWrite(3, 200);
//backup for 2 seconds
delay(2000);
//
//stopping
//
//brake both motors
digitalWrite(8, HIGH);
digitalWrite(9, HIGH);
}
//
//when nothing is within 12"
//the robot simply drives forwards
//
else{
//Setting drive motor
//
//set drive motor forward direction
digitalWrite(12, HIGH);
//turn off brake of drive motor
digitalWrite(9, LOW);
//activate drive motor
analogWrite(3, 20);
}
delay(100);
}