Skip to content
English

Colour Sensor

The colour sensor looks at the floor, so it tells the robot about holes, swamps and passages. It is a camera of a single pixel, pointing down. On the starter robot it is named color, at the front of the robot, so that it sees a hole before the wheels reach it.

from controller import Robot
robot = Robot()
timeStep = int(robot.getBasicTimeStep())
colorSensor = robot.getDevice("color")
colorSensor.enable(timeStep)
while robot.step(timeStep) != -1:
image = colorSensor.getImage() # A single pixel
r = colorSensor.imageGetRed(image, 1, 0, 0)
g = colorSensor.imageGetGreen(image, 1, 0, 0)
b = colorSensor.imageGetBlue(image, 1, 0, 0)
print("r:", r, "g:", g, "b:", b)

These values were measured with the starter robot on world2.wbt:

Floor Red Green Blue
Normal 252 252 252
Swamp 245 222 142
Passage between areas 1 and 2 (blue) 91 91 255
Passage between areas 2 and 3 (purple) 193 91 251
Passage between areas 1 and 4 (green) 48 255 48
Passage between areas 3 and 4 (red) 255 91 91

Holes have a black edge, so the floor gets dark just before a hole. Checkpoints look almost like normal floor to this sensor, so calibrate on one in your world.

This program drives forward, prints the floor each time it changes, and stops if it sees a hole:

from controller import Robot
robot = Robot()
timeStep = int(robot.getBasicTimeStep())
colorSensor = robot.getDevice("color")
colorSensor.enable(timeStep)
leftWheel = robot.getDevice("left wheel motor")
rightWheel = robot.getDevice("right wheel motor")
leftWheel.setPosition(float("inf"))
rightWheel.setPosition(float("inf"))
def floorType(r, g, b):
# Tune these ranges for your own robot and worlds
brightness = (r + g + b) / 3
if brightness < 80:
return "hole"
if r > 220 and g > 200 and b < 190:
return "swamp"
if b > 220 and g < 130:
return "purple passage" if r > 150 else "blue passage"
if r > 220 and g < 130 and b < 130:
return "red passage"
if g > 220 and r < 100 and b < 100:
return "green passage"
return "floor"
leftWheel.setVelocity(3.0)
rightWheel.setVelocity(3.0)
last = None
while robot.step(timeStep) != -1:
image = colorSensor.getImage()
floor = floorType(colorSensor.imageGetRed(image, 1, 0, 0),
colorSensor.imageGetGreen(image, 1, 0, 0),
colorSensor.imageGetBlue(image, 1, 0, 0))
if floor != last:
print("Floor:", floor)
last = floor
if floor == "hole": # Stop before falling in
leftWheel.setVelocity(0)
rightWheel.setVelocity(0)
break