How to use an Android sensor event to determine if a device is up or down

I have a pretty simple requirement. Assuming the device is at its end, perpendicular to the ground, and it is tilted, all I need to do is determine if the phone is tilted forward or backward (the screen is larger to the ground or closer to the ceiling).

I know how to read values โ€‹โ€‹from different sensors, and I believe that using the TYPE_ROTATION_VECTOR sensor is the way forward. All that I am missing is the mathematical know-how to determine forward or backward from the three return values.

I read all the related threads on SO without enlightenment, any help is much appreciated.

+4
source share
3 answers
float[] rotationMatrix = new float[9]; float[] inclinationMatrix = new float[9]; float[] accelerometer; // values from sensor float[] magnetic; // values from sensor SensorManager.getRotationMatrix(rotationMatrix, inclinationMatrix, accelerometer, magnetic) int inclination = (int) Math.round(Math.toDegrees(Math.acos(rotationMatrix[8]))); if (inclination < 90) { // face up } if (inclination > 90) { // face down } 
+3
source

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

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

 X is defined as the vector product YZ (It is tangential to the ground at the device current location and roughly points East). Y is tangential to the ground at the device current location and points towards magnetic north. Z points towards the sky and is perpendicular to the ground. 

In your case, try this,

 if(Round(y,4) < 8.0){ Log.d("sensor", "=====UP===="); } else if(Round(y,4) < -8.0){ Log.d("sensor", "=====DOWN===="); } 

accelerometer sensor

+1
source

You can use the accelerometer and magnetic field sensor to detect this.

I found this useful blog post that has the necessary code to show you how to do this.

http://www.ahotbrew.com/how-to-detect-forward-and-backward-tilt/

0
source

All Articles