ジャイロと加速度センサー
ジャイロスコープ
Section titled “ジャイロスコープ”ジャイロスコープは、各軸まわりのロボットの回転速度を ラジアン毎秒 で返します。スターターロボットでは 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 ラジアン以内で一致しました。小さな誤差もゲーム中に積み重なるので、たとえば壁に合わせるなどして、できるときに向きを補正しましょう。
加速度センサー
Section titled “加速度センサー”加速度センサーは、各軸方向の加速度を m/s² で返します。スターターロボットでは accelerometer という名前です。静止しているとき、getValues()[1] は重力にあたる約 9.8 になります。
慣性計測ユニット
Section titled “慣性計測ユニット”慣性計測ユニット(inertial unit)はスターターロボットには付いていません。Robot Customizer で追加でき、デフォルトの名前は inertial_unit です。回転速度を足し合わせなくても、getRollPitchYaw() で向きを直接得られます。Webots のリファレンスを参照してください。
