How to stop a servo using conditional if?

I'm using an Arduino Uno, Ultrasonic sensor (HC-SR04) and a Servo motor (SG90 Tower Pro).


I would like to rotate the servo continuously from 0 to 180 and back to 0.

I would like to stop the servo whenever the ultrasonic sensor detects an object at a distance of 40 cm or less.

I know how to rotate the servo and how to detect an object using the ultrasonic sensor, but I couldn't combine the two.

Can you kindly help me on how to do so?

if(detect_object)Stop_servo();

You have code that sweeps the servo back and forth? Great!
You have code that detects distance using the that sensor? Great!

I could probably better help yo combine them if you posted those two sketches. Please use the code tags when you do. See the stick post titles "How to use this forum - please read." at the top of this forum if you do not know how.

Then post the sketch that is your attempt to combine the two.
Tell us what you expected it to do, and what it did that differed from that.

If we assume you start with the sketch File->Examples->Servo->Sweep you have loops for moving the servo in little steps:

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

You want the motion to only happen when the distance is less than 40cm so you make the motion conditional:

void loop() {
  distance = getDistanceCM();
  // Do a full sweep if the distance is "Out Of Range" (0) or > 40 CM
  if (distance == 0 || distance > 40) {
    for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
      // in steps of 1 degree
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      delay(15);                       // waits 15ms for the servo to reach the position
    }
    for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      delay(15);                       // waits 15ms for the servo to reach the position
    }
  }
}

That version will always do full sweeps over and back. If you want the servo to stop more immediately you will need to check the distance inside the loops. This will slow down the sweep motion.