跳到內容
中文(繁體)

第一個程式

你的第一個程式會讓機器人往前走,並在牆前停下來。它很短,但具備了每個程式都需要的一切。

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. 把程式儲存為 hello.py。
  2. 開啟 game/worlds/mapping_example_1.wbt,用右邊的 LOAD 按鈕載入入門機器人。
  3. 用左邊的 LOAD 按鈕載入 hello.py,然後按下開始。

機器人會往前走,Webots 主控台會顯示它與前方牆壁的距離,直到機器人停下來。如果你看到的是錯誤訊息,請查看疑難排解。

  • 把速度從 3.0 改成 6.0。接近牆壁時會發生什麼事?
  • 讓機器人在 10 cm 而不是 5 cm 處停下來。
  • 也用 robot.getTime() 印出時間。

接下來,在移動中學習如何前進和轉彎。