Uroš Trstenjak
Uroš Trstenjak

Reputation: 903

How to detect one full turn (360 degrees) of the phone?

Since I did not find any relevant answers searching the web, I am posting a question regarding detection of 360 degrees turns of android devices around its axes using the accelerometer. For example around y-axis in landscape mode: let us say that in starting position y value is 0 (device is flat to ground). When phone is rotated forward for 90 degrees y = -10, 180 degrees forward tilt would result in y = 0, 270 degrees tilt in y = +10 and 360 degrees in y = 0. So how would the code look like to detect this full turn of the device only in prespecified direction?

@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
    // assign directions
    x = event.values[1];
    y = event.values[0];
    z = event.values[2];

        ???
    }
}

EDIT: Have succeded by using getRotationMatrix() method.

private float[] r = new float[9];
private float[] i = new float[9];
private float[] v = new float[3];

private float[] accValues = new float[3];
private float[] geoValues = new float[3];

private int azimuth, pitch, roll;

@Override
public void onSensorChanged(SensorEvent event) {

    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        accValues = event.values.clone();
    }

    if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
        geoValues = event.values.clone();
    }

    boolean success = SensorManager.getRotationMatrix(r, i, accValues,
        geoValues);

    if (success) {
        SensorManager.getOrientation(r, v);

        azimuth = v[0] * (180 / Math.PI);
        pitch = v[1] * (180 / Math.PI);
        roll = v[2] * (180 / Math.PI);
    }
}

Upvotes: 3

Views: 2801

Answers (1)

user2497624
user2497624

Reputation: 159

You might try something like :

`
@Override

public void onSensorChanged(SensorEvent event) {

if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {

x = event.values[1];
y = event.values[0];
z = event.values[2];

if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
x1 = event.values[1];
y1 = event.values[0];
z1 = event.values[2];

}

}`

This code should allow you to detect a change in acceleration and orientation, so even if the Y value of the accelerometer goes from 0 to 0 again because there was a change in orientation then there was a full rotation (however, u still need to clean this code to eliminate the case where the phone goes 180° in a direction and then goes back 180° (turn the phone up and down again ))

Out of curiosity, why would you need a 360° turn of the phone? I tried to turn my phone 360°, it's not something easy to do.

Upvotes: 1

Related Questions