跳转到内容
中文(简体)

位置传感器

位置传感器,也就是 GPS,会给出机器人的位置,单位为米。在入门机器人上,它的名字是 gps。你需要用它来报告墙面标识,它对有条理地探索也很有帮助。

getValues() 返回 [x, y, z]。X 和 Z 是水平方向,Y 是竖直方向,所以要用 X 和 Z 表示机器人在迷宫中的位置:

水平面上的 X 轴和 Z 轴,Y 轴竖直向上

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))

GPS 有几毫米的噪声,所以即使机器人静止不动,数值也会略有变化。永远不要判断两个位置是否完全相等。

下面的程序让机器人向前行驶,直到它离开起点半个地块:

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