delay hang - motor shield and ultrasonic sensor

Hi all,

I guess this must be a common problem for newbies like me, I cant quite seem to get my head around it.

I want to control speed of a DC motor through the ultrasonic ping sensor

Everything is wired up ok - but when the duration argument is met, the sensor stops reading for the time specified by the delay values.

What I want is that the motor will run constantly when something is close (i.e. duration <18000), and stop when out of range, and for this motion to be constantly monitored:

here's the code:

#include <AFMotor.h>

AF_DCMotor motor1(1, MOTOR12_2KHZ);

int pingPin = 2;

void setup() {

Serial.begin(9600);
}

void loop() {

long duration;

pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);

pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);

Serial.print(duration);

Serial.println();

delay(100);

if (duration < 18000) {
motor1.setSpeed(20);

motor1.run(FORWARD);
delay(1000);

motor1.run(RELEASE);
delay(1000);

}

}

thanks for any advice (should i be looking at a millis, or attachInterupt
for example??)