Zum Inhalt springen
Deutsch

Positionssensor

Der Positionssensor, auch GPS genannt, gibt die Position des Roboters in Metern an. Beim Starter-Roboter heißt er gps. Du brauchst ihn, um Wandmarkierungen zu melden, und er hilft sehr dabei, systematisch zu erkunden.

getValues() gibt [x, y, z] zurück. X und Z sind horizontal, Y ist vertikal. Verwende also X und Z für die Position im Labyrinth:

Die X- und Z-Achse der horizontalen Ebene, Y vertikal

from controller import Robot
robot = Robot()
timeStep = int(robot.getBasicTimeStep())
gps = robot.getDevice("gps")
gps.enable(timeStep)
while robot.step(timeStep) != -1:
x, y, z = gps.getValues() # In meters. X and Z are horizontal, Y is vertical.
print("x:", round(x, 3), "z:", round(z, 3))

Das GPS hat ein Rauschen von wenigen Millimetern, daher ändern sich die Werte leicht, auch wenn der Roboter stillsteht. Vergleiche Positionen nie auf exakte Gleichheit.

Dieses Programm fährt vorwärts, bis der Roboter eine halbe Kachel von seinem Startpunkt entfernt ist:

from controller import Robot
import math
robot = Robot()
timeStep = int(robot.getBasicTimeStep())
gps = robot.getDevice("gps")
gps.enable(timeStep)
leftWheel = robot.getDevice("left wheel motor")
rightWheel = robot.getDevice("right wheel motor")
leftWheel.setPosition(float("inf"))
rightWheel.setPosition(float("inf"))
robot.step(timeStep) # Step once, so that the GPS has a value
startX, _, startZ = gps.getValues()
leftWheel.setVelocity(3.0)
rightWheel.setVelocity(3.0)
while robot.step(timeStep) != -1:
x, _, z = gps.getValues()
distance = math.sqrt((x - startX) ** 2 + (z - startZ) ** 2)
print("Distance from the start:", round(distance, 3), "m")
if distance > 0.06: # Half a tile
leftWheel.setVelocity(0)
rightWheel.setVelocity(0)
break