Obstacle avoidance with Gelo

Python code and building instructions for the LEGO MINDSTORMS Robot Inventor Main Models (51515).

Obstacle avoidance with Gelo
Image credit: LEGO

Gelo can autonomously roam around and avoid obstacles by using the ultrasonic sensor.


Quick start

This script makes use of the gelo.py module, so make sure to save that program in Pybricks Code first.

Then save the script below as gelo_roam.py and run it.

Gelo will walk forward until it “sees” an obstacle. Then it will randomly turn left or right then start walking again until it sees the next obstacle.

Program

from pybricks.parameters import Icon
from urandom import choice
from gelo import Gelo

with Gelo() as gelo:
    # If the ultrasonic sensor measures less than
    # 30 cm (1 ft), then we are too close!
    def too_close():
        return gelo.ultrasonic.distance() < 300

    while True:
        # walk until the ultrasonic sensor detects an obstruction
        gelo.hub.display.icon(Icon.ARROW_UP)
        gelo.walk_until(too_close)

        # randomly turn left or right to avoid the obstruction
        direction = choice(["left", "right"])

        if choice == "left":
            gelo.hub.display.icon(Icon.ARROW_LEFT)
            gelo.walk(steer=90, time=4000)
        else:
            gelo.hub.display.icon(Icon.ARROW_RIGHT)
            gelo.walk(steer=-90, time=4000)

Change it up

Try changing the program to attack obstacles instead avoiding them.

  • Change the main loop to turn until an obstacle is detected.
  • Then walk towards the obstacle until Gelo crashes into it!

This project was submitted by The Pybricks Team.