콘텐츠로 이동
한국어

거리 센서

거리 센서는 앞에 있는 첫 번째 물체까지의 거리를 최대 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)

센서는 로봇의 중심이 아니라 센서가 달린 위치에서 측정해요. 벽 옆에서 값을 출력해 보고 직접 기준값을 정하세요.