I'm trying to detect an upward motion on my Android device but am finding this quite difficult. I've written the following code, and it works for all sudden motion (i.e. fast acceleration) on all directions. However, I would like this to work only for a sudden upward motion. Any help is greatly appreciated.
public void onSensorChanged(SensorEvent event) {
// alpha is calculated as t / (t + dT)
// with t, the low-pass filter's time-constant
// and dT, the event delivery rate
final float alpha = 0.8f;
gravity = new float[3];
linear_acceleration = new float[3];
linear_acceleration_old = new float[3];
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];
linear_acceleration[0] = event.values[0] - gravity[0];
linear_acceleration[1] = event.values[1] - gravity[1];
linear_acceleration[2] = event.values[2] - gravity[2];
System.out.println(linear_acceleration[0] + " "
+ linear_acceleration[1]+" " +linear_acceleration[2]);
//detects swift movements, but I want to detect only upward ones
if((Math.abs(linear_acceleration[1] - linear_acceleration_old[1]) > 10.0f
&& Math.abs(linear_acceleration[2] - linear_acceleration_old[2]) > 5.0f)
|| isFirstEvent) {
if(!isFirstEvent)
//do something
linear_acceleration_old[0] = linear_acceleration[0];
linear_acceleration_old[1] = linear_acceleration[1];
linear_acceleration_old[2] = linear_acceleration[2];
isFirstEvent= false;
}
}
I'm not quite sure what you meant by "upward", however:
letting the phone rest on the table surface and lift it up (make it higher than the table), would be a change in Z axis.
vertically holding the phone as if you are talking and then pull it up (raise it higher), would be a change in Y axis.
If you are interested in detecting these motions, you should modify your code to calculate deltas only in the relevant axis.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With