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

回眸只為那壹抹淺笑 提交于 2019-12-11 04:47:23

问题


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);
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/17420999/how-to-detect-one-full-turn-360-degrees-of-the-phone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!