陀螺儀與加速度計
陀螺儀會回傳機器人繞各軸轉動的速度,單位是弧度每秒。在入門機器人上,它的名稱是 gyro。
getValues() 會回傳 [x, y, z]。Y 軸是垂直方向,所以 getValues()[1] 就是機器人的轉向速度。向左轉時為正值。
範例:轉 90 度
Section titled “範例:轉 90 度”把轉動速度乘以時間步長後累加起來,就能得到轉過的角度。這比用時間控制轉彎更可靠,因為它不受速度影響。
from controller import Robotimport math
robot = Robot()timestep = int(robot.getBasicTimeStep())
left = robot.getDevice("left wheel motor")right = robot.getDevice("right wheel motor")left.setPosition(float("inf"))right.setPosition(float("inf"))
gyro = robot.getDevice("gyro")gyro.enable(timestep)
def turnLeft(angle): turned = 0 left.setVelocity(-2) right.setVelocity(2) while abs(turned) < angle and robot.step(timestep) != -1: turned += gyro.getValues()[1] * timestep / 1000 # Speed multiplied by the time, in seconds left.setVelocity(0) right.setVelocity(0)
turnLeft(math.pi / 2)print("Turned 90 degrees")#include <cmath>#include <iostream>#include <webots/Robot.hpp>#include <webots/Motor.hpp>#include <webots/Gyro.hpp>
using namespace webots;
Robot *robot;Motor *leftMotor, *rightMotor;Gyro *gyro;int timeStep;
void turnLeft(double angle) { double turned = 0; leftMotor->setVelocity(-2); rightMotor->setVelocity(2); while (fabs(turned) < angle && robot->step(timeStep) != -1) turned += gyro->getValues()[1] * timeStep / 1000.0; // Speed multiplied by the time, in seconds leftMotor->setVelocity(0); rightMotor->setVelocity(0);}
int main() { robot = new Robot(); timeStep = (int)robot->getBasicTimeStep();
leftMotor = robot->getMotor("left wheel motor"); rightMotor = robot->getMotor("right wheel motor"); leftMotor->setPosition(INFINITY); rightMotor->setPosition(INFINITY);
gyro = robot->getGyro("gyro"); gyro->enable(timeStep);
turnLeft(M_PI / 2); std::cout << "Turned 90 degrees" << std::endl;
delete robot; return 0;}在入門機器人上的測試中,用這種方式算出的角度與實際轉動的誤差在 0.01 弧度以內。小誤差在一場比賽中會不斷累積,所以有機會時請修正方向,例如對齊牆壁。
加速度計會回傳沿各軸的加速度,單位是 m/s²。在入門機器人上,它的名稱是 accelerometer。靜止時,getValues()[1] 的讀數大約是 9.8,也就是重力。
慣性測量單元
Section titled “慣性測量單元”入門機器人上沒有慣性測量單元(inertial unit)。你可以用 Robot Customizer 加入一個,預設名稱是 inertial_unit。它會用 getRollPitchYaw() 直接提供方向,不需要自己累加轉動速度。請參閱 Webots 參考文件。
