Skip to content
English

Distance Sensor

A distance sensor measures the distance, in metres, to the first object in front of it, up to 0.8 m. The starter robot has three: leftDist, frontDist and rightDist, looking left, forward and right.

Three distance sensors seen from above, facing left, forward and right

from controller import Robot
robot = Robot()
timeStep = int(robot.getBasicTimeStep())
frontDist = robot.getDevice("frontDist") # Get the sensor by name
frontDist.enable(timeStep) # Enable it
while robot.step(timeStep) != -1:
print("Front:", round(frontDist.getValue(), 3), "m")

A tile is 12 cm wide, so when the robot is in the middle of a tile, a wall on its side is about 5 cm away. This program checks the three sensors, and prints which ones see a wall:

from controller import Robot
robot = Robot()
timeStep = int(robot.getBasicTimeStep())
# Keep the sensors in a dictionary, to use them by name
sensors = {}
for name in ["leftDist", "frontDist", "rightDist"]:
sensors[name] = robot.getDevice(name)
sensors[name].enable(timeStep)
WALL = 0.07 # Closer than 7 cm counts as a wall next to the robot
while robot.step(timeStep) != -1:
walls = [name for name, sensor in sensors.items() if sensor.getValue() < WALL]
print("Walls:", walls)

Sensors measure from where they are on the robot, not from its centre. Print the values next to a wall to choose your own limits.