Skip to content
English

Gyro and Accelerometer

The gyroscope returns the rotation speed of the robot around each axis, in radians per second. On the starter robot it is named gyro.

getValues() returns [x, y, z]. The Y axis is vertical, so getValues()[1] is the turning speed of the robot. It is positive when turning to the left.

Turning to the left gives a positive value, and turning to the right a negative value

Add up the rotation speed multiplied by the time step to get the angle turned. This is more reliable than timing the turn, because it does not depend on the speed.

from controller import Robot
import math
robot = Robot()
timestep = int(robot.getBasicTimeStep())
left = robot.getDevice("left wheel motor")
right = robot.getDevice("right wheel motor")
left.setPosition(float("inf"))
right.setPosition(float("inf"))
gyro = robot.getDevice("gyro")
gyro.enable(timestep)
def turnLeft(angle):
turned = 0
left.setVelocity(-2)
right.setVelocity(2)
while abs(turned) < angle and robot.step(timestep) != -1:
turned += gyro.getValues()[1] * timestep / 1000 # Speed multiplied by the time, in seconds
left.setVelocity(0)
right.setVelocity(0)
turnLeft(math.pi / 2)
print("Turned 90 degrees")

In a test on the starter robot, the angle calculated like this matched the real rotation to within 0.01 radians. Small errors add up over a game, so correct the heading when you can, for example by aligning with a wall.

The accelerometer returns the acceleration along each axis in m/s². On the starter robot it is named accelerometer. At rest, getValues()[1] reads about 9.8, which is gravity.

The inertial unit is not on the starter robot. With the Robot Customizer you can add one, named inertial_unit by default. It gives the orientation directly, with getRollPitchYaw(), instead of having to add up rotation speeds. See the Webots reference.