使用加速度计读取android手机的xyz坐标

Ruw*_*tha 16 android accelerometer android-2.3-gingerbread

我将开发Android应用程序,需要在3D空间上读取手机的x,y,z坐标.

我想在设备上编写一个简单的代码和测试..

我在设备和模拟器上都使用姜面包.

spo*_*tus 16

要从加速度获得位置,您需要将其集成两次.

积分加速度为您提供速度和积分速度为您提供位置.

请记住,集成噪声会产生漂移,并且积分漂移会产生很多漂移,因此安卓传感器往往会产生很多噪音.

在我的Galaxy S3上,使用谷歌的线性加速度计复合传感器,我可以在5秒钟内将漂移位置降至0.02米.

我不确定你是否可以在姜饼上使用线性加速计传感器.如果你不能,你必须在整合之前去除重力.

如果你还没有,请阅读这里的所有内容 http://developer.android.com/guide/topics/sensors/sensors_motion.html

关于android中运动传感器的精彩演讲

http://www.youtube.com/watch?v=C7JQ7Rpwn2k

码:

static final float NS2S = 1.0f / 1000000000.0f;
float[] last_values = null;
float[] velocity = null;
float[] position = null;
long last_timestamp = 0;

@Override
public void onSensorChanged(SensorEvent event) {
    if(last_values != null){
        float dt = (event.timestamp - last_timestamp) * NS2S;

        for(int index = 0; index < 3;++index){
            velocity[index] += (event.values[index] + last_values[index])/2 * dt;
            position[index] += velocity[index] * dt;
        }
    }
    else{
        last_values = new float[3];
        velocity = new float[3];
        position = new float[3];
        velocity[0] = velocity[1] = velocity[2] = 0f;
        position[0] = position[1] = position[2] = 0f;
    }
    System.arraycopy(event.values, 0, last_values, 0, 3);
    last_timestamp = event.timestamp;
}
Run Code Online (Sandbox Code Playgroud)

现在你在3d空间中占有一席之地,请记住它假设手机在开始采样时是静止的.

如果你不去除重力,很快就会很远.

这根本不会过滤数据,会产生很多漂移.

  • @spontus使用你的代码与线性加速度传感器,我与设备仍坐在办公桌上的位置值在x和y沿z增加约每秒1,和大约每秒10.这是你期望的吗?我知道这种方法不是很准确,但它应该是这么糟糕吗? (2认同)

Eig*_*ght 7

阅读本教程.

上面给出的教程的简短摘要::

首先获取SensorManagerSensor的实例.
里面onCreate()::

mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
Run Code Online (Sandbox Code Playgroud)

在此之后,覆盖onSensorChanged(SensorEvent event)并使用event.values[]以获得坐标.

@Override
public void onSensorChanged(SensorEvent event) {
    float x = event.values[0];
    float y = event.values[1];
    float z = event.values[2];
}
Run Code Online (Sandbox Code Playgroud)