Sensor inercial#

Introducción#

The inertial class is used to control and access data from an EXP Inertial Sensor. EXP can use the Brain’s built-in Inertial Sensor or an external Inertial Sensor connected to a Smart Port.

Un sensor inercial mide el movimiento y los giros del robot. El giroscopio mide la dirección, la rotación, la velocidad angular y la orientación. El acelerómetro mide los cambios de movimiento, como la aceleración o la desaceleración en los ejes x, y y z.

Constructores de clases#

inertial(
    int32_t  index,
    turnType dir = turnType::right );

Instructor de clase#

Destroys the inertial object and releases associated resources.

~inertial();

Parámetros#

Parámetro

Tipo

Descripción

index

int32_t

Optional. The Smart Port that an external Inertial Sensor is connected to, written as PORTx, where x is the port number (for example, PORT1). Do not include this parameter when using the Brain’s built-in Inertial Sensor.

dir

turnType

Optional. The direction that returns positive values:

  • right (default) — Right turns return positive values.
  • left — Left turns return positive values.

Ejemplos#

// Use the Brain's built-in Inertial Sensor.
inertial BrainInertial = inertial();

// Use an external Inertial Sensor connected to Port 1.
inertial Inertial1 = inertial(PORT1);

Funciones de los miembros#

The inertial class includes the following member functions:

  • heading — Returns the direction the sensor is facing.

  • rotation — Returns how far the sensor has turned.

  • setHeading — Sets the sensor’s current heading to a new heading value.

  • setRotation — Sets the sensor’s current rotation to a new rotation value.

  • calibrate — Calibrates the Inertial Sensor.

  • resetHeading — Resets the sensor’s current heading to 0 degrees.

  • resetRotation — Resets the sensor’s current rotation to 0 degrees.

  • isCalibrating — Returns whether the Inertial Sensor is currently calibrating.

  • changed — Registers a function to be called when the heading changes.

  • installed — Returns whether the Inertial Sensor is installed.

  • acceleration — Returns how quickly the sensor is speeding up or slowing down on the selected axis.

  • gyroRate — Returns how fast the sensor is rotating on the selected axis.

  • orientation — Returns the Inertial Sensor’s roll, pitch, or yaw angle.

  • collision — Registers a function to run when a collision is detected.

  • setTurnType — Sets which turn direction returns positive values.

  • getTurnType — Returns which turn direction produces positive values.

Before calling any inertial member functions, an inertial instance must be created, as shown below:

/* This constructor is required when using VS Code.
Inertial Sensor configuration is generated automatically
in VEXcode using the Device Menu. Replace the values
as needed. */

// Use the Brain's built-in Inertial Sensor.
inertial BrainInertial = inertial();

heading#

Devuelve la orientación actual del sensor inercial.

La orientación es la dirección hacia la que apunta el sensor, medida en grados de 0 a 359,99. Si el sensor gira más allá de los 359,99 grados, la orientación vuelve a 0 grados.

Available Functions
double heading( rotationUnits units = degrees );

Parameters

Parámetro

Tipo

Descripción

units

rotationUnits

The heading unit:

  • deg / degrees (default) — degrees
  • turns / rev — revolutions

Return Values

Returns a double representing the current heading of the sensor in the specified units.

Notes
  • The heading value is wrapped between 0 and 359.99 degrees. Use rotation to access the continuous rotation value.

Examples
// Turn, then show the current heading
Drivetrain.turnFor(right, 450, degrees);
Brain.Screen.print("%f", myInertial.heading(degrees));

rotation#

Devuelve la rotación actual del sensor inercial.

La rotación indica cuánto ha girado el sensor. A diferencia de la orientación, la rotación puede superar los 359,99 grados o disminuir por debajo de 0 grados. Por ejemplo, dos giros completos a la derecha dan como resultado una rotación de 720 grados. Un giro completo a la izquierda desde 0 grados da como resultado una rotación de -360 grados.

Available Functions
double rotation( rotationUnits units = degrees );

Parameters

Parámetro

Tipo

Descripción

units

rotationUnits

The rotation unit:

  • deg / degrees (default) — degrees
  • turns / rev — revolutions

Return Values

Returns a double representing the current rotation in the specified units.

Notes
  • The rotation value is continuous and does not wrap between 0 and 359.99 degrees. Use heading to access the wrapped heading value.

Examples
// Turn, then show the current rotation
Drivetrain.turnFor(right, 450, degrees);
Brain.Screen.print("%f", myInertial.rotation(degrees));

setHeading#

La orientación es la dirección hacia la que apunta el sensor, medida en grados de 0 a 359,99. Esta función cambia la orientación actual del sensor inercial a un nuevo valor.

Por ejemplo, si el sensor se ha girado hacia la derecha, al ajustar la orientación a 0 grados, esa posición hacia la derecha se convierte en la nueva dirección de 0 grados. De esta forma, el sensor puede seguir otras orientaciones basándose en esa nueva dirección.

Available Functions
void setHeading( double value, rotationUnits units );

Parameters

Parámetro

Tipo

Descripción

value

double

El valor de rumbo, en grados, que se configurará para el sensor. Este valor puede estar entre 0 y 359,99.

units

rotationUnits

The heading unit:

  • deg / degrees — degrees
  • turns / rev — revolutions

Return Values

Esta función no devuelve ningún valor.

Examples
// Turn the robot around
myInertial.setHeading(180, degrees);
Drivetrain.turnToHeading(0, degrees);

setRotation#

La rotación indica cuánto ha girado el sensor, medida en grados. A diferencia de la orientación, la rotación puede superar los 359,99 grados o disminuir por debajo de 0 grados. Al inicio de un proyecto, el valor de rotación se establece en 0 grados. Esta función cambia la rotación actual del sensor inercial a un nuevo valor.

Por ejemplo, si el sensor ha dado dos vueltas completas a la derecha, su valor de rotación será de 720 grados. Al establecer la rotación en 0 grados, esta volverá a su valor original. De esta forma, el sensor podrá registrar las rotaciones basándose en ese nuevo valor.

Available Functions
void setRotation( double value, rotationUnits units );

Parameters

Parámetro

Tipo

Descripción

value

double

El valor de rotación, en grados, que se configurará para el sensor. Puede ser un número entero o decimal.

units

rotationUnits

The rotation unit:

  • deg / degrees — degrees
  • turns / rev — revolutions

Return Values

Esta función no devuelve ningún valor.

Examples
// Turn the robot around
myInertial.setRotation(-180, degrees);
Drivetrain.turnToRotation(0, degrees);

calibrate#

Calibra el sensor inercial.

La calibración ayuda al sensor a medir los giros correctamente. Mantenga el sensor inmóvil durante la calibración. Si el sensor se mueve durante la calibración, es posible que los valores de rumbo, rotación, velocidad angular y orientación no se midan correctamente.

Available Functions
void calibrate( );

Parameters

Esta función no acepta ningún parámetro.

Return Values

Esta función no devuelve ningún valor.

Notes
  • El sensor debe permanecer inmóvil mientras se realiza la calibración.

  • Use isCalibrating to determine when calibration has completed.

resetHeading#

Restablece la orientación actual del sensor inercial a 0 grados.

Una vez utilizada esta función, la dirección actual del sensor se convierte en la nueva dirección de 0 grados.

Available Functions
void resetHeading();

Parameters

Esta función no requiere ningún parámetro.

Return Values

Esta función no devuelve ningún valor.

resetRotation#

Restablece la rotación actual del sensor inercial a 0 grados.

Una vez utilizada esta función, el sensor realiza un seguimiento de los giros futuros a partir del nuevo valor de rotación de 0 grados.

Available Functions
void resetRotation();

Parameters

Esta función no requiere ningún parámetro.

Return Values

Esta función no devuelve ningún valor.

isCalibrating#

Indica si el sensor inercial se está calibrando actualmente.

Available Functions
bool isCalibrating();

Parameters

Esta función no requiere ningún parámetro.

Return Values

Devuelve un valor booleano que indica si el sensor inercial se está calibrando:

  • true — The sensor is currently calibrating.
  • false — The sensor is not currently calibrating.

changed#

Registra una función de devolución de llamada que se ejecuta cuando cambia el valor de rumbo del sensor inercial.

Available Functions
void changed( void (* callback)(void) );

Parameters

Parámetro

Tipo

Descripción

callback

void (*)(void)

A pointer to a function that will be called when the heading value changes. The function must take no parameters and return void.

Return Values

Esta función no devuelve ningún valor.

Examples

Define the callback function (outside of int main())

// Called when the inertial sensor's heading value changes
void onHeadingChanged() {
  Brain.Screen.clearScreen();
  Brain.Screen.setCursor(1, 1);
  Brain.Screen.print("Heading: %.2f", myInertial.heading());
}

Register the callback inside int main()

/* vexcodeInit() is only required when using VEXcode.
Remove vexcodeInit() if compiling in VS Code. */
int main() {

  // Turn the robot by hand briefly
  // to change the robot's heading
  myInertial.changed(onHeadingChanged);
}

installed#

Indica si el sensor inercial está instalado y conectado.

Available Functions
bool installed();

Parameters

Esta función no requiere ningún parámetro.

Return Values

Devuelve un valor booleano que indica si el sensor inercial está instalado y conectado:

  • true — The sensor is connected and responding.
  • false — The sensor is not connected or not detected.

acceleration#

La aceleración indica la rapidez con la que el sensor aumenta o disminuye su velocidad. Esta función devuelve la aceleración del sensor inercial en el eje seleccionado, desde -4,0 G hasta 4,0 G.

A G is a unit used to measure acceleration. 1 G is about the acceleration you feel from gravity while sitting still. The value can be positive or negative depending on the direction of acceleration on the selected axis.

Available Functions
double acceleration( axisType axis );

Parameters

Parámetro

Tipo

Descripción

axis

axisType

The axis to measure acceleration on:

  • xaxis
  • yaxis
  • zaxis

Return Values

Returns a double representing the acceleration along the specified axis in G (gravitational units).

Notes
  • Acceleration values are reported in units of G.

gyroRate#

La velocidad del giroscopio indica la rapidez con la que gira el sensor inercial. Esta función devuelve la velocidad de rotación actual del sensor inercial en el eje seleccionado.

El valor puede ser positivo o negativo dependiendo de la dirección en la que gire el sensor sobre ese eje.

Available Functions
double gyroRate( axisType axis, velocityUnits units );

Parameters

Parámetro

Tipo

Descripción

axis

axisType

The axis to return the gyro rate from:

  • xaxis
  • yaxis
  • zaxis

units

velocityUnits

The gyro rate unit:

  • dps — degrees per second
  • rpm — revolutions per minute

Return Values

Returns a double representing the current rotation speed along the specified axis in the selected units.

Examples
// Display the rate of change of rotation while turning in dps
Drivetrain.turn(right);
wait(1, seconds);

Brain.Screen.print(myInertial.gyroRate(zaxis, dps));

Drivetrain.stop();

orientation#

La orientación es el ángulo actual del sensor inercial en un eje seleccionado. Esta función devuelve la orientación del sensor inercial, desde -180,00 hasta 180,00 grados.

El eje x, y o z seleccionado corresponde a uno de los ejes de orientación del sensor.

Available Functions
double orientation(
  axisType      axis,
  rotationUnits units );

Parameters

Parámetro

Tipo

Descripción

axis

axisType

The axis for which orientation is returned:

  • xaxis
  • yaxis
  • zaxis

units

rotationUnits

The rotation unit:

  • deg / degrees — degrees
  • turns / rev — revolutions

Return Values

Returns a double representing the selected orientation angle in the specified units.

Examples
while (true) {
  Brain.Screen.clearScreen();
  Brain.Screen.setCursor(1,1);
  // Show the Inertial Sensor's orientation value
  // for roll in degrees
  double orient = myInertial.orientation(xaxis, deg);
  Brain.Screen.print("%f", orient);
  wait(0.1, seconds);
}

collision#

Registra una función de devolución de llamada que se ejecuta cuando el sensor inercial detecta un impacto o colisión repentina.

Available Functions
void collision( void (* callback)(axisType, double, double, double) );

Parameters

Parámetro

Tipo

Descripción

callback

void (*)(axisType, double, double, double)

A pointer to a function that will be called when a collision is detected. The callback function must accept the following parameters:

  • axisType — The axis on which the collision was detected.
  • Acceleration values at the time of impact, in order:
    • double — Acceleration along the x-axis (in G).
    • double — Acceleration along the y-axis (in G).
    • double — Acceleration along the z-axis (in G).
The function must return void.

Return Values

Esta función no devuelve ningún valor.

Examples

Define the callback function (outside of int main())

// Called when the Inertial Sensor detects a collision
void onCollision(axisType axis, double x, double y, double z) {
  Brain.Screen.print("Collision detected!");
}

Register the callback inside int main()

/* vexcodeInit() is only required when using VEXcode.
Remove vexcodeInit() if compiling in VS Code. */
int main() {

  // Firmly move the robot by hand briefly to simulate
  // a collision and call the onCollision function
  myInertial.collision(onCollision);
}

setTurnType#

Los conjuntos que indican la dirección de giro devuelven valores positivos.

Available Functions
void setTurnType( turnType dir );

Parameters

Parámetro

Tipo

Descripción

dir

turnType

The direction that returns positive values:

  • right
  • left

Return Values

Esta función no devuelve ningún valor.

Notes

getTurnType#

Devuelve valores cuyo cambio de dirección produce valores positivos.

Available Functions
turnType getTurnType();

Parameters

Esta función no requiere ningún parámetro.

Return Values

Returns a turnType indicating which direction produces positive values:

  • right — Clockwise rotation returns positive values.
  • left — Counterclockwise rotation returns positive values.
Notes