如何上下抖动在Android中使用加速度计? [英] How to shake up and down using Accelerometer in Android?

查看:179
本文介绍了如何上下抖动在Android中使用加速度计?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试以下方法,但如果器件将保持在正常的方式,它并不完美..,然后还要它触发抖动事件。

I tried the following way, but it doesn't work perfectly.. If device is kept in normal way, then also it fires shake event.

@Override
public void onSensorChanged(SensorEvent event) {
    // TODO Auto-generated method stub

    long curTime = System.currentTimeMillis();
    // only allow one update every 200Ms.
    if ((curTime - lastUpdate) > 200) {

        lastUpdate = curTime;

        x = event.values[SensorManager.DATA_X];
        y = event.values[SensorManager.DATA_Y];
        z = event.values[SensorManager.DATA_Z];

        Vibrator vibrate = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

        if (Round(y, 4) > 22) {
            vibrate.vibrate(200);
            Log.d("sensor", "==== Up Detected===");

        } else if (Round(y, 4) < -20) {
            vibrate.vibrate(200);
            Log.d("sensor", "==== Down Detected=== ");

        }

        mLastX = x;
        mLastY = y;
        mLastZ = z;
    }

}

public static float Round(float Rval, int Rpl) {
    float p = (float) Math.pow(10, Rpl);

    Rval = Rval * p;
    float tmp = Math.round(Rval);
    return (float) tmp / p;
}

请帮助。

任何帮助将是非常美联社preciated ..

Any Help would be highly appreciated..

感谢

推荐答案

作为您的Y轴值应用低通滤波器。

Apply lowpass filter on as your y-axis values.

基本的过滤器会在文档中被提到。

The basic filter will be as mentioned in documentation.

public void onSensorChanged(SensorEvent event){
  // In this example, alpha is calculated as t / (t + dT),
 // where t is the low-pass filter's time-constant and
 // dT is the event delivery rate.

 final float alpha = 0.8;

 // Isolate the force of gravity with the low-pass filter.
 gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];
 gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];
 gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];

 // Remove the gravity contribution with the high-pass filter.
 linear_acceleration[0] = event.values[0] - gravity[0];
 linear_acceleration[1] = event.values[1] - gravity[1];
 linear_acceleration[2] = event.values[2] - gravity[2];
  }

这篇关于如何上下抖动在Android中使用加速度计?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆