The location sensor, also called the GPS, is used to retrieve the absolute x, y, and z position of the robot, useful for localizing the robot within the field. The units returned are in meters.
There are 4 basic steps to using this sensor:
Start by importing or including the appropriate class for the location 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.
Note: The horizontal plane of the sensor's coordinate system is defined by the X and Z axes. The Y axis is therefore the vertical axis:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from controller import Robot, GPS # Step 1: Import GPSrobot = Robot()
gps = robot.getDevice("gps") # Step 2: Retrieve the sensor, named "gps", from the robot. Note that the sensor name may differ between robotstimestep = int(robot.getBasicTimeStep())
gps.enable(timestep) # Step 3: Enable the sensor, using the timestep as the update ratewhile robot.step(timestep) !=-1:
x = gps.getValues()[0] # Step 4: Use the getValues() function to get the sensor readings y = gps.getValues()[1] # Note that the gps returns a list of 3 values for x, y, z, position z = gps.getValues()[2]
print("x: "+ str(x) +" y: "+ str(y) +" z: "+ str(z))
#include<iostream>#include<webots/Robot.hpp>#include<webots/GPS.hpp> // Step 1: Include GPS Headerusingnamespace webots;
usingnamespace std;
intmain(int argc, char**argv) {
Robot *robot =new Robot();
GPS* gps = robot->getGPS("gps"); // Step 2: Retrieve the sensor, named "gps", from the robot. Note that the sensor name may differ between robots.
int timeStep = (int)robot->getBasicTimeStep();
gps->enable(timeStep); // Step 3: Enable the sensor, using the timestep as the update rate
while (robot->step(timeStep) !=-1) {
double x = gps->getValues()[0]; // Step 4: use the getValues() function to get the sensor reading
double y = gps->getValues()[1]; // Note that the gps returns an array of 3 values for x, y, z, position
double z = gps->getValues()[2];
cout <<"x: "<< x <<" y: "<< y <<" z: "<< z << endl; // Print out the values of the sensor
}
delete robot;
return0;
}
Example
This sample gives an example application of the location sensor. It continuously prints the distance, calculated using the distance formula, from the starting position of the robot.
from controller import Robot, GPS
import math
robot = Robot()
gps = robot.getDevice("gps")
timestep = int(robot.getBasicTimeStep())
gps.enable(timestep)
robot.step(timestep) # Must step once to update sensor readingstartX = gps.getValues()[0] # Store initial robot position startZ = gps.getValues()[2]
while robot.step(timestep) !=-1:
x = gps.getValues()[0]
z = gps.getValues()[2]
dist = math.sqrt((x-startX)**2+ (z-startZ)**2); # Use the distance formula to calculate distance to starting position print("Distance from starting location: "+ str(dist))