거리 센서
거리 센서는 앞에 있는 첫 번째 물체까지의 거리를 최대 0.8 m까지 미터 단위로 측정해요. 스타터 로봇에는 왼쪽, 앞쪽, 오른쪽을 향하는 leftDist, frontDist, rightDist 세 개가 있어요.

센서 읽기
섹션 제목: “센서 읽기”from controller import Robot
robot = Robot()timeStep = int(robot.getBasicTimeStep())
frontDist = robot.getDevice("frontDist") # Get the sensor by namefrontDist.enable(timeStep) # Enable it
while robot.step(timeStep) != -1: print("Front:", round(frontDist.getValue(), 3), "m")#include <iostream>#include <webots/Robot.hpp>#include <webots/DistanceSensor.hpp>
using namespace webots;using namespace std;
int main() { Robot *robot = new Robot(); int timeStep = (int)robot->getBasicTimeStep();
DistanceSensor *frontDist = robot->getDistanceSensor("frontDist"); // Get the sensor by name frontDist->enable(timeStep); // Enable it
while (robot->step(timeStep) != -1) cout << "Front: " << frontDist->getValue() << " m" << endl;
delete robot; return 0;}벽 찾기
섹션 제목: “벽 찾기”타일의 너비는 12 cm이므로, 로봇이 타일 한가운데에 있을 때 옆의 벽은 약 5 cm 떨어져 있어요. 이 프로그램은 세 센서를 확인하고, 어느 센서가 벽을 보는지 출력해요.
from controller import Robot
robot = Robot()timeStep = int(robot.getBasicTimeStep())
# Keep the sensors in a dictionary, to use them by namesensors = {}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)#include <iostream>#include <string>#include <vector>#include <webots/Robot.hpp>#include <webots/DistanceSensor.hpp>
using namespace webots;using namespace std;
int main() { Robot *robot = new Robot(); int timeStep = (int)robot->getBasicTimeStep();
vector<string> names = {"leftDist", "frontDist", "rightDist"}; vector<DistanceSensor *> sensors; for (const string &name : names) { sensors.push_back(robot->getDistanceSensor(name)); sensors.back()->enable(timeStep); }
const double WALL = 0.07; // Closer than 7 cm counts as a wall next to the robot
while (robot->step(timeStep) != -1) { cout << "Walls:"; for (size_t i = 0; i < sensors.size(); i++) if (sensors[i]->getValue() < WALL) cout << " " << names[i]; cout << endl; }
delete robot; return 0;}센서는 로봇의 중심이 아니라 센서가 달린 위치에서 측정해요. 벽 옆에서 값을 출력해 보고 직접 기준값을 정하세요.
