How to make a motor react to a ultrasonic sensor

All I want to know is when coding a motor with an ultrasonic sensor, do I need to put my motors code before an if-statement or in it to get them to react with the sensor?

What code ?

Here comes code without tags.

Like if I code a servo motor with an ultrasonic sensor do I code the motor before or after an if statement

Oooh I wasn't expecting that! You're being asked to share your sketch.

include<Servo.h>
#define trigpin A0 // Trigger pin
#define echopin A1 // echo pin

Servo myservo1; // Left leg
Servo myservo2; // Right leg
int pos = 0;
int pos1= 100;
int pos2 = 90;
int pos3 = 80;



void setup() {
Serial.begin(9600);
myservo1.attach(9);
myservo2.attach(10);

pinMode(trigpin, OUTPUT);
pinMode(echopin, INPUT);

}

void loop ()
{
  
int duration, distance;
myservo1.write(pos);
myservo2.write(pos);
delay(400);
digitalWrite(trigpin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigpin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigpin, LOW);
  duration = pulseIn(echopin, HIGH);
  distance = duration*0.034/2;
  Serial.print(distance);
  Serial.println("cm");
  delay(50);
  
  
  if (distance > 10)
  {
    Serial.println("distance is less than or equal to");
    myservo1.write(pos1);
  delay(100);
  myservo1.write(pos2);
  delay(100);
  myservo2.write(pos1);
  delay(100);
  myservo2.write(pos2);
  delay(100);
  }
if (distance < 10)
{
  myservo1.write(pos3);
  delay(100);
  myservo1.write(pos2);
  delay(100);
  myservo2.write(pos3);
  delay(100);
  myservo2.write(pos2);
  delay(100);
}
}

That seems like a contradiction to me...

So seeing your question, and your code, I realize there is something missing needed to answer. What is the program supposed to do? How should it behave?

Ok so what can I do to get everything to work?

I want the servos to go backwards when the sensors hit a certain spot (10cm)

What happens now?

I get measurements from the sensor and my servos just move forward. Usually when I do the servo code after the if statement nothing happens.

Have you tested all your hardware with the simple example sketches provided with the servo library, to confirm that all the hardware is working? Also tested the ultrasonic sensor separately from this program?

I did it all works perfectly

Do you actually see values less than 10 in the serial monitor?

yes

So what seems to be the problem?

My sensor isn't triggering my servos to move backwards. I test my code again and once I put my hand in front of the sensors my servos speed just slows down abit.

How are your servos powered?

See reply #18