[proxy] web.archive.org← back | site home | direct (HTTPS) ↗ | proxy home | ◑ dark◐ light

SensorEvent  |  Android Developers

This class represents a Sensor event and holds information such as the sensor's type, the time-stamp, accuracy and of course the sensor's data.

Definition of the coordinate system used by the SensorEvent API.

The coordinate-system is defined relative to the screen of the phone in its default orientation. The axes are not swapped when the device's screen orientation changes.

The X axis is horizontal and points to the right, the Y axis is vertical and points up and the Z axis points towards the outside of the front face of the screen. In this system, coordinates behind the screen have negative Z values.

Note: This coordinate system is different from the one used in the Android 2D APIs where the origin is in the top-left corner.

values

public final float[] values

The length and contents of the values array depends on which sensor type is being monitored (see also SensorEvent for a definition of the coordinate system used).

Sensor.TYPE_ACCELEROMETER:

All values are in SI units (m/s^2)

A sensor of this type measures the acceleration applied to the device (Ad). Conceptually, it does so by measuring forces applied to the sensor itself (Fs) using the relation:

Ad = - ∑Fs / mass

In particular, the force of gravity is always influencing the measured acceleration:

Ad = -g - ∑F / mass

For this reason, when the device is sitting on a table (and obviously not accelerating), the accelerometer reads a magnitude of g = 9.81 m/s^2

Similarly, when the device is in free-fall and therefore dangerously accelerating towards to ground at 9.81 m/s^2, its accelerometer reads a magnitude of 0 m/s^2.

It should be apparent that in order to measure the real acceleration of the device, the contribution of the force of gravity must be eliminated. This can be achieved by applying a high-pass filter. Conversely, a low-pass filter can be used to isolate the force of gravity.


     public void onSensorChanged(SensorEvent event)
     {
          // alpha is calculated as t / (t + dT)
          // with t, the low-pass filter's time-constant
          // and dT, the event delivery rate

          final float alpha = 0.8;

          gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];
          gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];
          gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];

          linear_acceleration[0] = event.values[0] - gravity[0];
          linear_acceleration[1] = event.values[1] - gravity[1];
          linear_acceleration[2] = event.values[2] - gravity[2];
     }
 

Examples:

Sensor.TYPE_MAGNETIC_FIELD:

All values are in micro-Tesla (uT) and measure the ambient magnetic field in the X, Y and Z axis.

Sensor.TYPE_GYROSCOPE:

All values are in radians/second and measure the rate of rotation around the device's local X, Y and Z axis. The coordinate system is the same as is used for the acceleration sensor. Rotation is positive in the counter-clockwise direction. That is, an observer looking from some positive location on the x, y or z axis at a device positioned on the origin would report positive rotation if the device appeared to be rotating counter clockwise. Note that this is the standard mathematical definition of positive rotation and does not agree with the definition of roll given earlier.

Typically the output of the gyroscope is integrated over time to calculate a rotation describing the change of angles over the time step, for example:

     private static final float NS2S = 1.0f / 1000000000.0f;
     private final float[] deltaRotationVector = new float[4]();
     private float timestamp;

     public void onSensorChanged(SensorEvent event) {
          // This time step's delta rotation to be multiplied by the current rotation
          // after computing it from the gyro sample data.
          if (timestamp != 0) {
              final float dT = (event.timestamp - timestamp) * NS2S;
              // Axis of the rotation sample, not normalized yet.
              float axisX = event.values[0];
              float axisY = event.values[1];
              float axisZ = event.values[2];

              // Calculate the angular speed of the sample
              float omegaMagnitude = sqrt(axisX*axisX + axisY*axisY + axisZ*axisZ);

              // Normalize the rotation vector if it's big enough to get the axis
              if (omegaMagnitude > EPSILON) {
                  axisX /= omegaMagnitude;
                  axisY /= omegaMagnitude;
                  axisZ /= omegaMagnitude;
              }

              // Integrate around this axis with the angular speed by the time step
              // in order to get a delta rotation from this sample over the time step
              // We will convert this axis-angle representation of the delta rotation
              // into a quaternion before turning it into the rotation matrix.
              float thetaOverTwo = omegaMagnitude * dT / 2.0f;
              float sinThetaOverTwo = sin(thetaOverTwo);
              float cosThetaOverTwo = cos(thetaOverTwo);
              deltaRotationVector[0] = sinThetaOverTwo * axisX;
              deltaRotationVector[1] = sinThetaOverTwo * axisY;
              deltaRotationVector[2] = sinThetaOverTwo * axisZ;
              deltaRotationVector[3] = cosThetaOverTwo;
          }
          timestamp = event.timestamp;
          float[] deltaRotationMatrix = new float[9];
          SensorManager.getRotationMatrixFromVector(deltaRotationMatrix, deltaRotationVector);
          // User code should concatenate the delta rotation we computed with the current
          // rotation in order to get the updated rotation.
          // rotationCurrent = rotationCurrent * deltaRotationMatrix;
     }
 

In practice, the gyroscope noise and offset will introduce some errors which need to be compensated for. This is usually done using the information from other sensors, but is beyond the scope of this document.

Sensor.TYPE_LIGHT:

Sensor.TYPE_PRESSURE:

Sensor.TYPE_PROXIMITY:

Note: Some proximity sensors only support a binary near or far measurement. In this case, the sensor should report its maximum range value in the far state and a lesser value in the near state.

Sensor.TYPE_GRAVITY:

A three dimensional vector indicating the direction and magnitude of gravity. Units are m/s^2. The coordinate system is the same as is used by the acceleration sensor.

Note: When the device is at rest, the output of the gravity sensor should be identical to that of the accelerometer.

Sensor.TYPE_LINEAR_ACCELERATION:

A three dimensional vector indicating acceleration along each device axis, not including gravity. All values have units of m/s^2. The coordinate system is the same as is used by the acceleration sensor.

The output of the accelerometer, gravity and linear-acceleration sensors must obey the following relation:

Sensor.TYPE_ROTATION_VECTOR:

The rotation vector represents the orientation of the device as a combination of an angle and an axis, in which the device has rotated through an angle θ around an axis <x, y, z>.

The three elements of the rotation vector are <x*sin(θ/2), y*sin(θ/2), z*sin(θ/2)>, such that the magnitude of the rotation vector is equal to sin(θ/2), and the direction of the rotation vector is equal to the direction of the axis of rotation.

The three elements of the rotation vector are equal to the last three components of a unit quaternion <cos(θ/2), x*sin(θ/2), y*sin(θ/2), z*sin(θ/2)>.

Elements of the rotation vector are unitless. The x,y, and z axis are defined in the same way as the acceleration sensor.

The reference coordinate system is defined as a direct orthonormal basis, where:

values[3], originally optional, will always be present from SDK Level 18 onwards. values[4] is a new value that has been added in SDK Level 18.

Sensor.TYPE_ORIENTATION:

All values are angles in degrees.

Note: This definition is different from yaw, pitch and roll used in aviation where the X axis is along the long side of the plane (tail to nose).

Note: This sensor type exists for legacy reasons, please use rotation vector sensor type and getRotationMatrix() in conjunction with remapCoordinateSystem() and getOrientation() to compute these values instead.

Important note: For historical reasons the roll angle is positive in the clockwise direction (mathematically speaking, it should be positive in the counter-clockwise direction).

Sensor.TYPE_RELATIVE_HUMIDITY:

When relative ambient air humidity and ambient temperature are measured, the dew point and absolute humidity can be calculated.

Dew Point

The dew point is the temperature to which a given parcel of air must be cooled, at constant barometric pressure, for water vapor to condense into water.

                    ln(RH/100%) + m·t/(Tn+t)
 td(t,RH) = Tn · ------------------------------
                 m - [ln(RH/100%) + m·t/(Tn+t)]
 
td
dew point temperature in °C
t
actual temperature in °C
RH
actual relative humidity in %
m
17.62
Tn
243.12 °C

for example:

 h = Math.log(rh / 100.0) + (17.62 * t) / (243.12 + t);
 td = 243.12 * h / (17.62 - h);
 
Absolute Humidity

The absolute humidity is the mass of water vapor in a particular volume of dry air. The unit is g/m3.

                    RH/100%·A·exp(m·t/(Tn+t))
 dv(t,RH) = 216.7 · -------------------------
                           273.15 + t
 
dv
absolute humidity in g/m3
t
actual temperature in °C
RH
actual relative humidity in %
m
17.62
Tn
243.12 °C
A
6.112 hPa

for example:

 dv = 216.7 *
 (rh / 100.0 * 6.112 * Math.exp(17.62 * t / (243.12 + t)) / (273.15 + t));
 

Sensor.TYPE_AMBIENT_TEMPERATURE:

Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED:

Similar to Sensor.TYPE_MAGNETIC_FIELD, but the hard iron calibration is reported separately instead of being included in the measurement. Factory calibration and temperature compensation will still be applied to the "uncalibrated" measurement. Assumptions that the magnetic field is due to the Earth's poles is avoided.

The values array is shown below:

x_uncalib, y_uncalib, z_uncalib are the measured magnetic field in X, Y, Z axes. Soft iron and temperature calibrations are applied. But the hard iron calibration is not applied. The values are in micro-Tesla (uT).

x_bias, y_bias, z_bias give the iron bias estimated in X, Y, Z axes. Each field is a component of the estimated hard iron calibration. The values are in micro-Tesla (uT).

Hard iron - These distortions arise due to the magnetized iron, steel or permanent magnets on the device. Soft iron - These distortions arise due to the interaction with the earth's magnetic field.

Sensor.TYPE_GAME_ROTATION_VECTOR:

Identical to Sensor.TYPE_ROTATION_VECTOR except that it doesn't use the geomagnetic field. Therefore the Y axis doesn't point north, but instead to some other reference, that reference is allowed to drift by the same order of magnitude as the gyroscope drift around the Z axis.

In the ideal case, a phone rotated and returning to the same real-world orientation will report the same game rotation vector (without using the earth's geomagnetic field). However, the orientation may drift somewhat over time. See Sensor.TYPE_ROTATION_VECTOR for a detailed description of the values. This sensor will not have the estimated heading accuracy value.

Sensor.TYPE_GYROSCOPE_UNCALIBRATED:

All values are in radians/second and measure the rate of rotation around the X, Y and Z axis. An estimation of the drift on each axis is reported as well.

No gyro-drift compensation is performed. Factory calibration and temperature compensation is still applied to the rate of rotation (angular speeds).

The coordinate system is the same as is used for the Sensor.TYPE_ACCELEROMETER Rotation is positive in the counter-clockwise direction (right-hand rule). That is, an observer looking from some positive location on the x, y or z axis at a device positioned on the origin would report positive rotation if the device appeared to be rotating counter clockwise. The range would at least be 17.45 rad/s (ie: ~1000 deg/s).

Pro Tip: Always use the length of the values array while performing operations on it. In earlier versions, this used to be always 3 which has changed now.

Sensor.TYPE_POSE_6DOF:

A TYPE_POSE_6DOF event consists of a rotation expressed as a quaternion and a translation expressed in SI units. The event also contains a delta rotation and translation that show how the device?s pose has changed since the previous sequence numbered pose. The event uses the cannonical Android Sensor axes.

Sensor.TYPE_STATIONARY_DETECT:

A TYPE_STATIONARY_DETECT event is produced if the device has been stationary for at least 5 seconds with a maximal latency of 5 additional seconds. ie: it may take up anywhere from 5 to 10 seconds afte the device has been at rest to trigger this event. The only allowed value is 1.0.

Sensor.TYPE_MOTION_DETECT:

A TYPE_MOTION_DETECT event is produced if the device has been in motion for at least 5 seconds with a maximal latency of 5 additional seconds. ie: it may take up anywhere from 5 to 10 seconds afte the device has been at rest to trigger this event. The only allowed value is 1.0.

Sensor.TYPE_HEART_BEAT:

A sensor of this type returns an event everytime a heart beat peak is detected. Peak here ideally corresponds to the positive peak in the QRS complex of an ECG signal.

A confidence value of 0.0 indicates complete uncertainty - that a peak is as likely to be at the indicated timestamp as anywhere else. A confidence value of 1.0 indicates complete certainly - that a peak is completely unlikely to be anywhere else on the QRS complex.

Sensor.TYPE_LOW_LATENCY_OFFBODY_DETECT:

A sensor of this type returns an event every time the device transitions from off-body to on-body and from on-body to off-body (e.g. a wearable device being removed from the wrist would trigger an event indicating an off-body transition). The event returned will contain a single value to indicate off-body state:

Valid values for off-body state:

When a sensor of this type is activated, it must deliver the initial on-body or off-body event representing the current device state within 5 seconds of activating the sensor.

This sensor must be able to detect and report an on-body to off-body transition within 1 second of the device being removed from the body, and must be able to detect and report an off-body to on-body transition within 5 seconds of the device being put back onto the body.

Sensor.TYPE_ACCELEROMETER_UNCALIBRATED:

All values are in SI units (m/s^2) Similar to Sensor.TYPE_ACCELEROMETER, Factory calibration and temperature compensation will still be applied to the "uncalibrated" measurement.

The values array is shown below:

x_uncalib, y_uncalib, z_uncalib are the measured acceleration in X, Y, Z axes similar to the Sensor.TYPE_ACCELEROMETER, without any bias correction (factory bias compensation and any temperature compensation is allowed). x_bias, y_bias, z_bias are the estimated biases.

Sensor.TYPE_HINGE_ANGLE:

A sensor of this type measures the angle, in degrees, between two integral parts of the device. Movement of a hinge measured by this sensor type is expected to alter the ways in which the user may interact with the device, for example by unfolding or revealing a display.

Sensor.TYPE_HEAD_TRACKER:

A sensor of this type measures the orientation of a user's head relative to an arbitrary reference frame, as well as the rate of rotation. Events produced by this sensor follow a special head-centric coordinate frame, where:

Data is provided in Euler vector representation, which is a vector whose direction indicates the axis of rotation and magnitude indicates the angle to rotate around that axis, in radians. The first three elements provide the transform from the (arbitrary, possibly slowly drifting) reference frame to the head frame. The magnitude of this vector is in range [0, π] radians, while the value of individual axes is in range [-π, π]. The next three elements optionally provide the estimated rotational velocity of the user's head relative to itself, in radians per second. If a given sensor does not support determining velocity, these elements are set to 0.

Sensor.TYPE_ACCELEROMETER_LIMITED_AXES:

Equivalent to TYPE_ACCELEROMETER, but supporting cases where one or two axes are not supported. The last three values represent whether the acceleration value for a given axis is supported. A value of 1.0 indicates that the axis is supported, while a value of 0 means it isn't supported. The supported axes should be determined at build time and these values do not change during runtime. The acceleration values for axes that are not supported are set to 0. Similar to Sensor.TYPE_ACCELEROMETER.

Sensor.TYPE_GYROSCOPE_LIMITED_AXES:

Equivalent to TYPE_GYROSCOPE, but supporting cases where one or two axes are not supported. The last three values represent whether the angular speed value for a given axis is supported. A value of 1.0 indicates that the axis is supported, while a value of 0 means it isn't supported. The supported axes should be determined at build time and these values do not change during runtime. The angular speed values for axes that are not supported are set to 0. Similar to Sensor.TYPE_GYROSCOPE.

Sensor.TYPE_ACCELEROMETER_LIMITED_AXES_UNCALIBRATED:

Equivalent to TYPE_ACCELEROMETER_UNCALIBRATED, but supporting cases where one or two axes are not supported. The last three values represent whether the acceleration value for a given axis is supported. A value of 1.0 indicates that the axis is supported, while a value of 0 means it isn't supported. The supported axes should be determined at build time and these values do not change during runtime. The acceleration values and bias values for axes that are not supported are set to 0.

Sensor.TYPE_GYROSCOPE_LIMITED_AXES_UNCALIBRATED:

Equivalent to TYPE_GYROSCOPE_UNCALIBRATED, but supporting cases where one or two axes are not supported. The last three values represent whether the angular speed value for a given axis is supported. A value of 1.0 indicates that the axis is supported, while a value of 0 means it isn't supported. The supported axes should be determined at build time and these values do not change during runtime. The angular speed values and drift values for axes that are not supported are set to 0.

Sensor.TYPE_HEADING:

A sensor of this type measures the direction in which the device is pointing relative to true north in degrees. The value must be between 0.0 (inclusive) and 360.0 (exclusive), with 0 indicating north, 90 east, 180 south, and 270 west. Accuracy is defined at 68% confidence. In the case where the underlying distribution is assumed Gaussian normal, this would be considered one standard deviation. For example, if heading returns 60 degrees, and accuracy returns 10 degrees, then there is a 68 percent probability of the true heading being between 50 degrees and 70 degrees.