跳转到内容
中文(简体)

移动

机器人有两个车轮,每个车轮都有自己的电机:在入门机器人上分别是 left wheel motor 和 right wheel motor。你通过设置每个车轮的速度来驾驶它:

左轮 右轮 机器人会……
向前 向前 向前行驶
向后 向后 向后行驶
向后 向前 原地向左转
向前 向后 原地向右转
快 慢 向右转弯

机器人向前行驶、向后行驶、原地向左转、原地向右转和向右转弯,箭头表示每个车轮的速度

速度的单位是弧度每秒,最大为 6.28(每秒车轮转一圈)。速度为负值时,车轮向后转。

  1. 按名字获取每个电机。
  2. 把它的位置设为无穷大,让它可以无限制地转动。
  3. 设置它的速度。

电机会保持你最后设置的速度,所以在程序做其他事情时,机器人会继续移动。下面的程序让机器人向前行驶、向后行驶、原地向左转,每个动作持续一秒:

from controller import Robot
robot = Robot()
timeStep = int(robot.getBasicTimeStep())
maxSpeed = 6.28 # The maximum speed of the wheels, in radians per second
leftWheel = robot.getDevice("left wheel motor")
rightWheel = robot.getDevice("right wheel motor")
leftWheel.setPosition(float("inf"))
rightWheel.setPosition(float("inf"))
def drive(left, right, seconds):
# Set the speed of each wheel, and keep it for some time
leftWheel.setVelocity(left)
rightWheel.setVelocity(right)
start = robot.getTime()
while robot.step(timeStep) != -1:
if robot.getTime() - start >= seconds:
break
drive(maxSpeed, maxSpeed, 1.0) # Forward
drive(-maxSpeed, -maxSpeed, 1.0) # Backward
drive(-2.0, 2.0, 1.0) # Spin to the left
drive(0, 0, 0.1) # Stop
print("Done")

每个电机都有一个位置传感器,也叫编码器,它以弧度为单位记录车轮转过了多少。它可以用来行驶固定的距离。车轮向后转时,计数会减小。

from controller import Robot
robot = Robot()
timeStep = int(robot.getBasicTimeStep())
leftWheel = robot.getDevice("left wheel motor")
rightWheel = robot.getDevice("right wheel motor")
leftWheel.setPosition(float("inf"))
rightWheel.setPosition(float("inf"))
# Each wheel has a position sensor, which counts how far it has turned
leftEncoder = leftWheel.getPositionSensor()
rightEncoder = rightWheel.getPositionSensor()
leftEncoder.enable(timeStep)
rightEncoder.enable(timeStep)
robot.step(timeStep) # Step once, so that the sensors have a value
start = leftEncoder.getValue()
leftWheel.setVelocity(5.0)
rightWheel.setVelocity(5.0)
while robot.step(timeStep) != -1:
turned = leftEncoder.getValue() - start
if turned > 10.0: # Stop after 10 radians
break
leftWheel.setVelocity(0)
rightWheel.setVelocity(0)
print("Left wheel:", round(leftEncoder.getValue() - start, 2), "rad")

按时间控制移动很简单,但结果会随速度而变化。编码器测量的是移动本身,所以更可靠。要想精确转向,陀螺仪效果更好。

接下来,学习如何读取传感器。