コンテンツにスキップ
日本語

最初のプログラム

最初のプログラムは、ロボットを前進させ、壁の手前で止めます。短いプログラムですが、どのプログラムにも必要なものがすべて入っています。

from controller import Robot
robot = Robot()
timeStep = int(robot.getBasicTimeStep())
# Get the devices of the starter robot by name
leftWheel = robot.getDevice("left wheel motor")
rightWheel = robot.getDevice("right wheel motor")
frontDist = robot.getDevice("frontDist")
# Sensors must be enabled before use
frontDist.enable(timeStep)
# Let the wheels turn without limit, and start driving forward
leftWheel.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 milliseconds
while 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
  1. ロボットを作成します。 Robot() で、プログラムをシミュレーター内のロボットにつなぎます。
  2. タイムステップを取得します。 シミュレーションは数ミリ秒ずつのステップで進みます。getBasicTimeStep() はワールドのステップを返します。
  3. デバイスを取得します。 各モーターとセンサーは名前で見つけます。これは、ロボットを組み立てたときに付けた名前です。
  4. センサーを有効にします。 センサーは有効にするまで値を返しません。タイムステップは、どのくらいの頻度で更新するかをセンサーに伝えます。
  5. ループします。 robot.step(timeStep) はシミュレーションを 1 ステップ進め、シミュレーションが終わると -1 を返します。ロボットのすべての動作は、このループの中で行われます。
  1. プログラムを hello.py として保存します。
  2. game/worlds/mapping_example_1.wbt を開き、右側の LOAD ボタンでスターターロボットを読み込みます。
  3. 左側の LOAD ボタンで hello.py を読み込み、スタートを押します。

ロボットが前進し、止まるまでの間、正面の壁までの距離が Webots のコンソールに表示されます。代わりにエラーが表示された場合は、トラブルシューティングを確認してください。

  • 速度を 3.0 から 6.0 に変えてみましょう。壁の近くで何が起こりますか?
  • 5 cm ではなく 10 cm で止まるようにしてみましょう。
  • robot.getTime() で時間も表示してみましょう。

次は、移動で走行と旋回を学びましょう。