Skip to content

2.2 Ultrasonic Obstacle Avoidance Program Block by Block

1. Start the Program

1. Drag the block "when Arduino Uno starts up".

Image 91

2. Attach the "forever" loop. Everything will go inside this forever loop.

Image 92

2. Read the Distance

1. Inside the loop, add a set variable block. Create a variable called distance. 2. Configure it: set distance to ultrasonic sensor reading (Trig A4 Echo A5)

This lets the robot know how far the obstacle is.

Image 93 Image 94

3. Add an IF Block

1. Inside the forever block, add an IF block: if ultrasonic sensor distance < 20 cm then

This triggers when an object is closer than 20 cm.

Image 95 Image 96

4. Stop the Robot

Inside the IF block, add: - run motor 2 forward speed 0% - run motor 3 forward speed 0%

The robot stops.

Image 97

5. Move Backward

Still inside the IF block, add: - run motor 2 backward speed 50% - run motor 3 backward speed 50% - wait 1 seconds

The robot moves away from the obstacle.

Image 98

6. Turn the Robot

Still inside the IF block, add: - run motor 2 forward speed 80% - run motor 3 backward speed 80% - wait 1 seconds

The robot turns to avoid the obstacle.

Image 99

7. Move Forward When Path Is Clear

Now add an ELSE clause. Inside ELSE, add: - run motor 2 forward speed 90% - run motor 3 forward speed 90%

The robot moves forward when there are no obstacles.

Image 100

Final Simple Logic

  1. Start
  2. Forever Loop
  3. If obstacle < 20 cm
    • Stop
    • Go backward
    • Turn
  4. Else
    • Move forward

Image 101

That is the full obstacle-avoiding robot program.

Image 102 Image 103