跳到內容
中文(繁體)

位置感測器

位置感測器(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