Create an advanced maze-solving algorithm that uses the gyroscope for precise 90° turns, implements a wall-following strategy, and organises code with functions for a clean, efficient solution.
Advanced maze in the Robot Simulator
Setup
Build the most challenging maze you can. Use narrow pathways with only 3–5 cm clearance on each side. Include loops, multiple paths, and dead ends. Add coloured sections on the floor for bonus tasks like changing speed or playing different sounds.
Building On Maze II
In Maze II we used all three distance sensors to make better decisions. Now we’ll add the gyroscope for precise turning, use functions to organise our code, and implement a proper wall-following algorithm.
Stage 1: Precise Turns with the Gyroscope
Instead of turning for a set time (which can be inaccurate), use the gyroscope to measure exactly how far the Rover has turned. Create a function called turnRight that turns the Rover exactly 90° by reading the gyroscope and stopping when the target angle is reached. Do the same for turnLeft.
def turnRight():
start = IMU.readGyroAccum(2) # Z-axis
Motors.turn(-30)
while abs(IMU.readGyroAccum(2) - start) < 90:
delay(0.01)
Motors.write(0)
def turnLeft():
start = IMU.readGyroAccum(2)
Motors.turn(30)
while abs(IMU.readGyroAccum(2) - start) < 90:
delay(0.01)
Motors.write(0)Stage 2: Wall-Following Algorithm
Implement a left-hand or right-hand wall-following strategy. The idea is simple: always keep a wall on one side. If the wall disappears (an opening), turn that direction. If a wall is ahead, turn the other way. This strategy guarantees the Rover will eventually find the exit in any simply-connected maze.
WALL = 10 # cm
def followLeftWall():
front = Ultrasonic.read()
left = IR.readLeft()
if left > WALL:
# Opening to the left, go that way
turnLeft()
Motors.moveDistance(15)
elif front < WALL:
# Wall ahead, turn right
turnRight()
else:
# Keep moving forward along the left wall
Motors.write(20)Stage 3: Organise With Functions
Create functions for each behaviour: moveForward, turnLeft, turnRight, checkWalls, and checkFinish. Your main loop should read cleanly as a series of function calls, this makes the code easier to debug and modify.
while True:
if checkFinish():
celebrate()
break
followLeftWall()Stage 4: Speed Optimisation
Once your Rover can reliably solve the maze, optimise for speed. Move faster in straight sections and slow down when approaching walls or turns. Use the distance sensor readings to adjust speed dynamically.
Challenge
Can you solve the maze as fast as possible? Time your Rover and try to beat your personal best. Compare times with classmates to see who has the most efficient algorithm.


