첫 번째 프로그램
첫 번째 프로그램은 로봇을 앞으로 주행시키다가 벽 앞에서 멈춰 세워요. 짧지만, 모든 프로그램에 필요한 것이 다 들어 있어요.
from controller import Robot
robot = Robot()timeStep = int(robot.getBasicTimeStep())
# Get the devices of the starter robot by nameleftWheel = robot.getDevice("left wheel motor")rightWheel = robot.getDevice("right wheel motor")frontDist = robot.getDevice("frontDist")
# Sensors must be enabled before usefrontDist.enable(timeStep)
# Let the wheels turn without limit, and start driving forwardleftWheel.setPosition(float("inf"))rightWheel.setPosition(float("inf"))leftWheel.setVelocity(3.0)rightWheel.setVelocity(3.0)
# The main loop: each step, the simulation advances by timeStep millisecondswhile robot.step(timeStep) != -1: distance = frontDist.getValue() print("Distance to the wall in front:", round(distance, 3), "m")
if distance < 0.05: # Closer than 5 cm: stop leftWheel.setVelocity(0) rightWheel.setVelocity(0) print("Wall reached!") break#include <iostream>#include <cmath>#include <webots/Robot.hpp>#include <webots/Motor.hpp>#include <webots/DistanceSensor.hpp>
using namespace webots;using namespace std;
int main() { Robot *robot = new Robot(); int timeStep = (int)robot->getBasicTimeStep();
// Get the devices of the starter robot by name Motor *leftWheel = robot->getMotor("left wheel motor"); Motor *rightWheel = robot->getMotor("right wheel motor"); DistanceSensor *frontDist = robot->getDistanceSensor("frontDist");
// Sensors must be enabled before use frontDist->enable(timeStep);
// Let the wheels turn without limit, and start driving forward leftWheel->setPosition(INFINITY); rightWheel->setPosition(INFINITY); leftWheel->setVelocity(3.0); rightWheel->setVelocity(3.0);
// The main loop: each step, the simulation advances by timeStep milliseconds while (robot->step(timeStep) != -1) { double distance = frontDist->getValue(); cout << "Distance to the wall in front: " << distance << " m" << endl;
if (distance < 0.05) { // Closer than 5 cm: stop leftWheel->setVelocity(0); rightWheel->setVelocity(0); cout << "Wall reached!" << endl; break; } }
delete robot; return 0;}작동 방식
섹션 제목: “작동 방식”- 로봇을 만들어요.
Robot()은 프로그램을 시뮬레이터 안의 로봇과 연결해요. - 타임 스텝을 가져와요. 시뮬레이션은 몇 밀리초 단위의 스텝으로 진행돼요.
getBasicTimeStep()은 월드의 스텝을 줘요. - 장치를 가져와요. 각 모터와 센서는 이름으로 찾아요. 로봇을 조립할 때 붙인 이름이에요.
- 센서를 활성화해요. 센서는 활성화되기 전에는 값을 주지 않아요. 타임 스텝은 얼마나 자주 업데이트할지 알려 줘요.
- 루프를 돌아요.
robot.step(timeStep)은 시뮬레이션을 한 스텝 진행시키고, 시뮬레이션이 끝나면 -1을 반환해요. 로봇이 하는 모든 일은 이 루프 안에서 일어나요.
실행하기
섹션 제목: “실행하기”- 프로그램을
hello.py로 저장하세요. game/worlds/mapping_example_1.wbt를 열고, 오른쪽 LOAD 버튼으로 스타터 로봇을 불러오세요.- 왼쪽 LOAD 버튼으로
hello.py를 불러오고, 시작 버튼을 누르세요.
로봇이 앞으로 주행하고, 로봇이 멈출 때까지 Webots 콘솔에 앞쪽 벽까지의 거리가 표시돼요. 대신 오류가 보이면 문제 해결을 확인하세요.
해 보기
섹션 제목: “해 보기”- 속도를
3.0에서6.0으로 바꿔 보세요. 벽 근처에서 무슨 일이 일어나나요? - 로봇이 5 cm 대신 10 cm에서 멈추게 해 보세요.
robot.getTime()으로 시간도 출력해 보세요.
다음으로 이동에서 주행과 회전을 배워 보세요.
