跳到內容
中文(繁體)

距離感測器

距離感測器會測量它正前方第一個物體的距離,單位是公尺,最遠 0.8 m。入門機器人有三個距離感測器:leftDist、frontDist 和 rightDist,分別朝向左方、前方和右方。

從上方看到的三個距離感測器,分別朝向左方、前方和右方

from controller import Robot
robot = Robot()
timeStep = int(robot.getBasicTimeStep())
frontDist = robot.getDevice("frontDist") # Get the sensor by name
frontDist.enable(timeStep) # Enable it
while robot.step(timeStep) != -1:
print("Front:", round(frontDist.getValue(), 3), "m")

一個地塊寬 12 cm,所以當機器人位於地塊中央時,旁邊的牆大約在 5 cm 外。這個程式會檢查三個感測器,並印出哪些感測器偵測到牆:

from controller import Robot
robot = Robot()
timeStep = int(robot.getBasicTimeStep())
# Keep the sensors in a dictionary, to use them by name
sensors = {}
for name in ["leftDist", "frontDist", "rightDist"]:
sensors[name] = robot.getDevice(name)
sensors[name].enable(timeStep)
WALL = 0.07 # Closer than 7 cm counts as a wall next to the robot
while robot.step(timeStep) != -1:
walls = [name for name, sensor in sensors.items() if sensor.getValue() < WALL]
print("Walls:", walls)

感測器是從它在機器人上的位置開始測量,而不是從機器人的中心。把機器人放在牆邊印出數值,再決定你自己的門檻值。