Get tilt angle from the android accelerometer
Asked Answered
O

3

9

I have a class that implements SensorEventListener and I would like to get the tilt Angle of my device using the Accelerometer.

I looked for examples on the internet but they use Sensor.TYPE_MAGNETIC_FIELD.

I believe my device doesn't have this sensor because when I do the following check
manager.getSensorList(Sensor.TYPE_ACCELEROMETER).size(), I get zero.

Is there a way to get the tilt Angle by just using Sensor.TYPE_ACCELEROMETER values?

Oralle answered 22/8, 2012 at 4:44 Comment(0)
B
3

As people suggested you can use the accelerometer and magnetic sensor to do this.

Here is a blog post with a complete solution.

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

Bergius answered 22/3, 2015 at 11:8 Comment(0)
L
1

Try this,

SensorManager sensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);        

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


            public void onSensorChanged(SensorEvent event) {
                // TODO Auto-generated method stub
                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;
                }
            };
        };

        setListners(sensorManager, mEventListener);

SensorManager.getRotationMatrix(mRotationMatrix, null, mValuesAccel, mValuesMagnet);
                SensorManager.getOrientation(mRotationMatrix, mValuesOrientation);
                final CharSequence test;
                test = ","+mValuesOrientation[0] +","+mValuesOrientation[1]+ ","+ mValuesOrientation[2];
Lefty answered 29/8, 2012 at 10:10 Comment(4)
As I said my device dont have Sensor.TYPE_MAGNETIC_FIELD. Is there a way to get the tilt Angle by just using Sensor.TYPE_ACCELEROMETER values?Oralle
then use only Sensor.TYPE-Accelerometer caseLefty
But then mValuesMagnet will be null, and it cant be.Oralle
I am having the same problem. Most devices I tested have both, and the code works great, but this one bastard device only has accelerometer, so I have to somehow use only that.Daman
S
1

You can use the accelerometer to get a tilt reading. If you set up an accelerometer you will notice it includes the force of gravity. So if you phone is face-up on a table the z-axis will register somewhere close to 9.81 (the force of gravity) and the x and y axes will be at 0. As you tilt the phone the force of gravity will be projected onto the x and/or y axis. Thus you the x and y values will tell you the tilt of the phone.

Swampland answered 9/2, 2014 at 22:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.