# Ultrasonic Sensor SRF-04 to run a high torque DC motor

Hi everyone
I wish to have a 12V DC motor running bi-directionally using L293D using output from the sensor. I have gone through the forum and done up this code using an if-else statement. If you could point me for any mistakes or improvements it would be a great help.
#/code

#define ECHOPIN 2 // Pin to receive echo pulse
#define TRIGPIN 3 // Pin to send trigger pulse
int motorpin1=5;
int motorpin2=4;
void setup(){
Serial.begin(9600);
pinMode(ECHOPIN, INPUT);
pinMode(TRIGPIN, OUTPUT);
pinMode(motorpin1,OUTPUT);
pinMode(motorpin2,OUTPUT);
}

void loop(){
digitalWrite(TRIGPIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGPIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGPIN, LOW);
int distance = pulseIn(ECHOPIN, HIGH);
distance= distance/58;
Serial.println(distance);

if(distance<5)
{

digitalWrite(motorpin1,HIGH);
digitalWrite(motorpin2,LOW);
delay(6000);
}
else if(distance>=5)
{
digitalWrite(motorpin1,LOW);
digitalWrite(motorpin2,HIGH);
}
else
{

delay(50);

}
}

Sannan

If the number is not less than five, it isn't necessary to test again to see if it is greater than or equal to five.

pulseIn does not return an int

Maybe some consistency in using "const int" or "#define", but not both for pin names

``````if(distance<5)
{
}
else if(distance>=5)
{
}
else
{
}
``````

If the value is less than 5 do one thing. Else, if the value is greater than or equal 5, do something else. Doesnâ€™t leave a whole hell of a lot of values that are not less than 5, equal to 5, or greater than 5, does it?

@ AWOL will definitely look into your idea and thanks for that pulseIn tip

@PaulS I had to have a precise point of 5 to be taken care of... your suggestion is well received thanks again..