Obstacle Avoidance

SPIKE Prime Robotics Camp — Day 4

 

 

 

 

Give your robot eyes

The Camp

  1. First Drive
  2. Maze Runner
  3. Gyro Precision
  4. Obstacle Avoidance (today!)
  5. Line Following + Showcase

Each day upgrades our robot.

Today's Mission

Give your robot eyes:

  • Read a distance sensor
  • Decide with if / else
  • React instead of following a script

The robot reacts to the world, not just to your code.

Rule of the Week

Bugs are sensor data.

The robot did exactly what the code said.
What did the code actually say?

Red Light / Green Light

Keep watching the signal and react.

Green = move, red = freeze.

That's a sensor loop: check, decide, do — over and over.

Catch-Up First

Make sure your robot still drives and turns.

Then plug in and mount the distance sensor.

Blocks or Python?

  • Blocks — drag and drop
  • Python — type it out

Same robot, same ideas. Pybricks shows the Python next to your blocks.

The Distance Sensor

The ultrasonic sensor measures how far away things are.

Add It in Setup


from pybricks.pupdevices import UltrasonicSensor

eyes = UltrasonicSensor(Port.C)   # use YOUR port
					

Plug it in and use the real port.

Read the Number


print(eyes.distance())   # millimeters
					

Move your hand closer — watch the number drop.

Nothing in front? It reads 2000 mm.

Make a Decision

If something's close, do one thing. Otherwise, do another.

if / else


if eyes.distance() < 200:
    robot.straight(-100)   # back up
    robot.turn(90)         # turn away
else:
    robot.drive(150, 0)    # forward, no turn
					

200 mm is a guess — measure and adjust.

Keep Checking: while

Check the sensor again and again, forever.

The Forever Loop


while True:
    if eyes.distance() < 200:
        robot.straight(-100)
        robot.turn(90)
    else:
        robot.drive(150, 0)
    wait(10)
					

Stopping It

  • while True: runs forever
  • Use the editor's Stop button

It won't stop on its own — that's expected.

Energizer + Snack

Get up, move, refuel.

Keep food away from the kits and laptops!

Build It

React to obstacles on the course.

Tune the Trigger

  1. Start near 200 mm
  2. Stops too early → smaller number
  3. Bumps the wall → bigger number

Measure on the real course.

Challenge

Don't fall off the table!

Sense the edge (or wall) and back away in time.

Demo + Wrap-Up

What We Learned

  • Read a sensor with distance() (mm)
  • 2000 mm means nothing detected
  • if / else makes decisions
  • while True: keeps checking — Stop button ends it

Coming Up Next

Line Following + Showcase

We'll teach the robot to follow a line with the color sensor —
steering in proportion to how far off it is —
then show off everything from the week.

Questions?

Great sensing!