Help! urgent! coding a motor to stop when Ultrasonic sensor detects obstacle

Hi, I am a total noob when it comes to coding and I am having a lot of difficulty with this project I am working on. I am trying to build an autonomous toy car that simply has to run until it comes in contact with an obstacle and then stop. I have all components (motor and sensor) hooked up to the arduino properly and have the code for the ultrasonic sensor running perfectly. The car runs and the sensor measures distances (through the serial monitor), however I don't know how to code it so that when the ultrasonic sensor detects a object 15cm or closer, to cut the motor. please help!

here is the code so far (the motor is running directly off of pin 13 for simplicity):

#define trigPin 3
#define echoPin 2
#define MAX_DISTANCE 200

void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(13, OUTPUT);
}

void loop() {
digitalWrite(13, HIGH);
int duration, distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
Serial.print(distance);
Serial.println(" cm");
delay(250);
}

With that set up, just a simple if:

Serial.print(distance);
Serial.println(" cm");
if (distance < 15)
{
   digitalWrite(13, LOW);
}

But you'll need to figure out what to do once it stops.... 8)

Please say you don't have the motor hooked up straight to an i/o pin: hopefully through a transistor?

Am I too late? Did it crash :frowning:

it still doesn't work for some reason...

and yes, it is through a transistor.

Circuit diagram please.

If you force pin 13 LOW does the motor turn off ?
Where is the power for the motor coming from ?

it still doesn't work for some reason

Not helpful.

What do the debug prints tell you?