The distance sensors in Erebus are configured to have a range between 0 to 0.8 meters. They will return the distance to the first object blocking their line of sight.
There are 4 basic steps to using this sensor:
Start by importing or including the appropriate class for the distance sensor.
Retrieve the sensor by name from the robot.
Enable the sensor by passing in the update rate of the sensor. (Usually the timestep)
Finally, retrieve values from the sensor.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from controller import Robot, DistanceSensor # Step 1: Import DistanceSensorrobot = Robot()
distanceSensor = robot.getDevice("ps0") # Step 2: Retrieve the sensor, named "ps0", from the robot. Note that the sensor name may differ between robotstimestep = int(robot.getBasicTimeStep())
distanceSensor.enable(timestep) # Step 3: Enable the sensor, using the timestep as the update ratewhile robot.step(timestep) !=-1:
distance = distanceSensor.getValue() # Step 4: Use the getValue() function to get the sensor reading print("Distance: "+ str(distance)) # Print out the value of the sensor
#include<iostream>#include<webots/Robot.hpp>#include<webots/DistanceSensor.hpp> // Step 1: Include DistanceSensorusingnamespace webots;
usingnamespace std;
intmain(int argc, char**argv) {
Robot *robot =new Robot();
DistanceSensor* distanceSensor = robot->getDistanceSensor("ps0"); // Step 2: Retrieve the sensor, named "ps0", from the robot. Note that the sensor name may differ between robots.
int timeStep = (int)robot->getBasicTimeStep();
distanceSensor->enable(timeStep); // Step 3: Enable the sensor, using the timestep as the update rate
while (robot->step(timeStep) !=-1) {
double distance = distanceSensor->getValue(); // Step 4: use the getValue() function to get the sensor reading
cout <<"Distance: "<< distance << endl; // Print out the value of the sensor
}
delete robot;
return0;
}
Example
This example shows how to enable, poll, and print values from multiple distance sensors using a list or array. This is useful for managing multiple distance sensors:
from controller import Robot, DistanceSensor
robot = Robot()
distanceSensors = [] # Create list to store the distance sensorstimestep = int(robot.getBasicTimeStep())
# Use a for loop to retrieve and enable the distance sensorsfor i in range(8):
distanceSensors.append(robot.getDevice("ps"+ str(i)))
distanceSensors[i].enable(timestep)
while robot.step(timestep) !=-1:
# Print the values of the 8 distance sensors for distanceSensor in distanceSensors:
distance = distanceSensor.getValue()
print("Distance: "+ str(distance))