Get tilt angle from the android accelerometer

﹥>﹥吖頭↗ 提交于 2020-01-03 08:34:19

问题


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?


回答1:


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/




回答2:


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];



回答3:


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.



来源:https://stackoverflow.com/questions/12066422/get-tilt-angle-from-the-android-accelerometer

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