Author Options:

How to stop a servo using conditional if? Answered

I'm using an Arduino Uno, Ultrasonic sensor (HC-SR04) 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?


The forums are retiring in 2021 and are now closed for new topics and comments.

2 years ago

You have several potential issues. Your Arduino only does one thing at a time so if it is moving the servo it isn't listening to the US module.

You need to do this in the form:


Move a little, send receive

If no signal then if servo not at end loop to start

This will scan, check, scan, check - so if you detect an object you can jump from the scan routine to the object avoidance.


Answer 2 years ago

The HC-SR04 module needs to be triggered and then a check for an object made and the distance calculated then you can decide what to do.

In actual fact in all the HC-SR04 sensor robots I have built the detection field is wide enough not to bother scanning - You can do as well just by looking forward.

Trust me

Reading and doing the following WILL help you a lot


Something like


Move servo 10 deg

trigger HC-SR04

Check for object

if object <100 mm then avoid

If not go to start


Turn right 20 deg

goto start


2 years ago

Something like this, in pseudocode, will work I thinl

while TRUE

{ check range

if (range >40 cm) servo position=servo position +increment

if servo position>=180 then increment =-1 else if (servoposition<=0) increment =+1

move servo (servo position)