2

Imagine you are pointing at the TV. You have your phone gripped in your hand. Now, rotate your wrist.

Which sensor would I need to manage to detect such a movement?

Gyroscope? Orientation? Accelerometer?

Vincent Mimoun-Prat
  • 28,208
  • 16
  • 81
  • 124
richard
  • 87
  • 1
  • 2
  • 7

3 Answers3

7

The sensors TYPE_MAGNETIC_FIELD and TYPE_ACCELEROMETER are fine to detect that (as TYPE_ORIENTATION is now deprecated).

You will need:

a few matrix:

private float[] mValuesMagnet      = new float[3];
private float[] mValuesAccel       = new float[3];
private float[] mValuesOrientation = new float[3];

private float[] mRotationMatrix    = new float[9];

a listener to catch the values the sensors send (this will be an argument of SensorManager.registerListener() that you will have to call to setup your sensors):

private final SensorEventListener mEventListener = new SensorEventListener() {
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    public void onSensorChanged(SensorEvent event) {
        // Handle the events for which we registered
        switch (event.sensor.getType()) {           
            case Sensor.TYPE_ACCELEROMETER: 
                System.arraycopy(event.values, 0, mValuesAccel, 0, 3); 
                break; 

            case Sensor.TYPE_MAGNETIC_FIELD: 
                System.arraycopy(event.values, 0, mValuesMagnet, 0, 3); 
                break; 
    }
};

And you'll need to compute the azimuth, pitch, and roll:

    SensorManager.getRotationMatrix(mRotationMatrix, null, mValuesAccel, mValuesMagnet);
    SensorManager.getOrientation(mRotationMatrix, mValuesOrientation);  

mValuesOrientation is then filled with:

  • mValuesOrientation[0]: azimuth, rotation around the Z axis.
  • mValuesOrientation[1]: pitch, rotation around the X axis.
  • mValuesOrientation[2]: roll, rotation around the Y axis.

Check the documentation of getOrientation() to know how the axis are defined. You may need to use SensorManager.remapCoordinateSystem() to redefine these axis.

Shlublu
  • 10,917
  • 4
  • 51
  • 70
  • When I do this, the pitch never goes to 180°. It starts at 0° (flat, facing the sky), then goes to 90° when the phone is facing me, then goes back to 90° when it faces the floor. Is that an expected behavior? How do I know if the device is staring the sky or the floor then? – Joan Nov 10 '14 at 14:58
0

The gyroscope is for detecting rotations if you don't care about your position relative to the Earth.

David Leppik
  • 3,194
  • 29
  • 18
0

It depends on what you want to detect, if you want to detect that the phone has been moved in a rotation then accelerometer is probably your best bet. If you want to detect that the phone is now rotated then Orientation.

Jim
  • 22,354
  • 6
  • 52
  • 80