Highway62
Highway62

Reputation: 800

How do I get rotation values for a single axis using Android's gyroscope?

I'm trying to get z-axis rotation values using the gyroscope in Android, I want to simply display the degrees that the phone is rotated around the z-axis on the screen. So if I'm holding the phone upright with the screen facing me, and rotate it 90 degrees to the right with the screen still facing me, I want it to show 90 degrees on the screen.

The code I have so far is pretty basic but I can't seem to find any examples of rotating only on a single axis:

I have a text view which simply prints out the data from onSensorChanged()

mySensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
List<Sensor> mySensors = mySensorManager.getSensorList(Sensor.TYPE_GYROSCOPE);

if(mySensors.size() > 0){
 mySensorManager.registerListener(mySensorEventListener, mySensors.get(0), SensorManager.SENSOR_DELAY_UI);
}

private SensorEventListener mySensorEventListener = new SensorEventListener() {

    @Override
    public void onSensorChanged(SensorEvent event) {

        textviewX.setText("X-Rotation: " + String.valueOf(event.values[0]));
        textviewY.setText("Y-Rotation " + String.valueOf(event.values[1]));
        textviewZ.setText("Z-Rotation " + String.valueOf(event.values[2]));
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }
};

The z-axis data it prints out when I rotate the phone on the z-axis just switches between 0, -0, 1, and 2, randomly as the phone rotates. Can anyone help me out here? Thanks.

Upvotes: 1

Views: 1651

Answers (1)

You are missing the fact that sensors do not return purely rotational values.

You need to account for gravity and precision.

See documentation

EDIT: I missed the fact that you need angular, not linear movement.

Manual still applies.

Upvotes: 0

Related Questions