跳转到内容
中文(简体)

距离传感器

距离传感器测量它前方第一个物体的距离,单位为米,最远 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)

传感器是从它们在机器人上的位置开始测量的,而不是从机器人的中心。把机器人放在墙边打印这些数值,然后选出你自己的阈值。