Skip to content
English

Your first program

Your first program drives the robot forward, and stops it in front of a wall. It is short, but it has everything every program needs.

from controller import Robot
robot = Robot()
timeStep = int(robot.getBasicTimeStep())
# Get the devices of the starter robot by name
leftWheel = robot.getDevice("left wheel motor")
rightWheel = robot.getDevice("right wheel motor")
frontDist = robot.getDevice("frontDist")
# Sensors must be enabled before use
frontDist.enable(timeStep)
# Let the wheels turn without limit, and start driving forward
leftWheel.setPosition(float("inf"))
rightWheel.setPosition(float("inf"))
leftWheel.setVelocity(3.0)
rightWheel.setVelocity(3.0)
# The main loop: each step, the simulation advances by timeStep milliseconds
while robot.step(timeStep) != -1:
distance = frontDist.getValue()
print("Distance to the wall in front:", round(distance, 3), "m")
if distance < 0.05: # Closer than 5 cm: stop
leftWheel.setVelocity(0)
rightWheel.setVelocity(0)
print("Wall reached!")
break
  1. Create the robot. Robot() connects your program to the robot in the simulator.
  2. Get the time step. The simulation advances in steps of a few milliseconds. getBasicTimeStep() gives the step of the world.
  3. Get the devices. Each motor and sensor is found by its name. These are the names you gave them when you built your robot.
  4. Enable the sensors. A sensor gives no values until it is enabled. The time step tells it how often to update.
  5. Loop. robot.step(timeStep) advances the simulation by one step, and returns -1 when the simulation ends. Everything your robot does happens inside this loop.
  1. Save the program as hello.py.
  2. Open game/worlds/mapping_example_1.wbt, and load the starter robot with the right LOAD button.
  3. Load hello.py with the left LOAD button, and press start.

The robot drives forward, and the Webots console shows the distance to the wall in front of it until the robot stops. If you see an error instead, check Troubleshooting.

  • Change the speed from 3.0 to 6.0. What happens near the wall?
  • Make the robot stop at 10 cm instead of 5 cm.
  • Print the time with robot.getTime() as well.

Next, learn to drive and turn in Movement.