通过加速度计和磁场传感器检测Android设备的倾斜和晃动

时间:2013-12-19 18:47:34

标签: android rotation accelerometer sensor magnetometer

目前我完全陷入大学锻炼。过去几天我一直在努力学习并做了很多研究,但要么我想做一些不可能的事情,要么我在推理中遇到了可怕的错误。

我的目标是什么? - 我想实现一个Android应用程序(android:minSdkVersion =“8”),这样就可以通过OSC发送反馈消息(正面或负面)。反馈发送不仅应该通过点击一些按钮(一个很容易;-)而且还可以通过摇动和倾斜设备来实现。

摇动意味着将智能手机从右向左旋转或反之亦然 - 就像摇头一样。倾斜意味着上下旋转设备 - 就像点头一样。

由于我的设备不是市场上最新鲜的,我只能使用加速度计和磁场传感器(我没有陀螺仪或其他东西)。

我基于谷歌搜索的想法是听取加速度计和磁场事件,并使用旋转矩阵来计算角度之间的增量。 x轴上的某个增量将被解释为倾斜(点头)并且y上的某个增量将会抖动。由于到目前为止我没有取得好成绩,我问自己这是否是正确的做法?!

目前我的SensorEventListener如下所示:

/**
 * TYPE_ACCELEROMETER
 * <ul>
 * <li>SensorEvent.values[0] Acceleration force along the x axis (including
 * gravity) in m/s2</li>
 * <li>SensorEvent.values[1] Acceleration force along the y axis (including
 * gravity) in m/s2</li>
 * <li>SensorEvent.values[2] Acceleration force along the z axis (including
 * gravity) in m/s2</li>
 * </ul>
 * 
 * TYPE_MAGNETIC_FIELD
 * <ul>
 * <li>SensorEvent.values[0] Geomagnetic field strength along the x axis in
 * µT</li>
 * <li>SensorEvent.values[1] Geomagnetic field strength along the y axis in
 * µT</li>
 * <li>SensorEvent.values[2] Geomagnetic field strength along the z axis in
 * µT</li>
 * </ul>
 */
@Override
public void onSensorChanged(SensorEvent event) {
    now = event.timestamp;

    // Handle the events for which we registered
    switch (event.sensor.getType()) {
    case Sensor.TYPE_ACCELEROMETER:
        System.arraycopy(event.values, 0, valuesAccelerometer, 0, 3);

        // no magnetic field data
        if (isArrayZeroFilled(valuesMagneticField)) {
            return;
        }

        // if rotation matrix cannot be retrieved
        if (!SensorManager.getRotationMatrix(null, rotationMatrix,
                valuesAccelerometer, valuesMagneticField))
            return;

        SensorManager.getOrientation(rotationMatrix, valuesOrientation);

        // valuesOrientation
        // values[0]: azimuth, rotation around the Z axis.
        // values[1]: pitch, rotation around the X axis.
        // values[2]: roll, rotation around the Y axis.

        zRotation = valuesOrientation[0];
        xRotation = valuesOrientation[1];
        yRotation = valuesOrientation[2];

        float xRotationDelta = Math.abs(xRotation - lastXRotation);
        System.out.println("x rotation delta " + xRotationDelta);

        float yRotationDelta = Math.abs(yRotation - lastYRotation);
        System.out.println("y rotation delta " + yRotationDelta);

        float zRotationDelta = Math.abs(zRotation - lastZRotation);
        System.out.println("z rotation delta " + zRotationDelta);

        break;

    case Sensor.TYPE_MAGNETIC_FIELD:
        System.arraycopy(event.values, 0, valuesMagneticField, 0, 3);
        break;
    }
}

奇怪的是,无论我如何移动或摇动手机,y和z增量始终为0.0。

我希望有人可以给我一些关于我的代码或思考中的错误的提示。

提前致谢!

1 个答案:

答案 0 :(得分:-1)

此代码可帮助您检测震动:1