我尝试了以下方法,但它并不完美。如果设备保持正常方式,那么它也会触发摇动事件。
@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;
}
请帮助。
任何帮助都将受到高度赞赏..
由于
答案 0 :(得分:0)
传感器值非常原始且噪音很大。您需要在它们之上添加一层数字信号处理以获得良好的结果。仅使用原始值将导致结果中出现大量抖动。你试图用你的时间延迟做一些基本的,但你需要做更多的过滤。
另外,你在震动时会振动。振动将导致加速度计看到运动,导致更多误报。
答案 1 :(得分:0)
将低通滤波器作为y轴值应用。
基本过滤器将如文档中所述。
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];
}