How to stop a servo using conditional if?

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?

rickharris9 days 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:

Start

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.

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

https://www.instructables.com/id/Starting-programm...

Something like

start

Move servo 10 deg

trigger HC-SR04

Check for object

if object <100 mm then avoid

If not go to start

avoid:

Turn right 20 deg

goto start

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)

}

iceng10 days ago

First take the free Arduino class and learn software it will be rewarding

https://www.instructables.com/class/Arduino-Class/

You will be glad to answer your own question !