Wandering Robot

The wandering robot algorithm is a great way to practice your obstacle avoidance skills. The idea is simple: you program the robot to randomly move without a goal or destination for as long as possible. The program can also be used for exploration or to map out environments.

The basic algorithm goes as follows:

  1. Random Direction: The robot randomly selects a direction to move (e.g., forward, backward, left, right).

  2. Movement: The robot moves in the selected direction for a predetermined distance or time.

  3. Obstacle Avoidance: If the robot encounters an obstacle, it randomly selects a new direction and tries again.

  4. Repeat: The process is repeated indefinitely, creating a seemingly random wandering pattern.

Mapping this out in a flow chart:

So let's implement it!

  1. First start the program:

Don’t forget to reverse the direction of the right side motors when initializing. This will make programming a lot easier!

  1. Next implement a random direction function.

To keep things simple, I will have the robot turn for a random amount of time before stopping. This will effectively spin the robot to a random orientation.

By having the right motors reverse when the left motors go forward, the robot can rotate in place. This is important as you don’t want the robot to get stuck while selecting a direction to proceed. The collision detection step isn’t active yet so getting stuck now will stop the robot.

Next, have the program sleep for a random amount of time. I choose between 0 and 2 seconds but this range can be anything.

  1. Obstacle Detection

There are multiple different ways of implementing this and you are highly encouraged to explore different methods. One of the easiest is using the distance sensor. Since the robot will be moving forwards, most of the obstacles will be in front of the robot so a distance sensor works well in most cases.

Here I use an if do else logic block. You know collision is imminent if there is an object present within 20 cm of the robot. The 20 cm gap is necessary as you need to give the robot space to turn and avoid the obstacle.

If there is no obstacle, move the robot forward.

If there is an obstacle, we can use the random turn code from earlier as an obstacle avoidance method. Afterall, there the random turn doesn’t avoid the obstacle, it will be quickly detected and the robot will turn until no obstacle is found.

Now just insert the Detect Obstacle function into the main program and run it on a loop. Voila! You have a working wandering robot code.

This is just one out of many versions of this code. One variant has the robot repeatedly turn left and right to try to widen the detection range of the distance sensor. Try to challenge yourself to create something better!