Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting sudden upward motion in Android

Tags:

android

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;
            }
        }
like image 881
OckhamsRazor Avatar asked Nov 06 '11 17:11

OckhamsRazor


1 Answers

I'm not quite sure what you meant by "upward", however:

  1. 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.

  2. 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.

like image 63
user1032613 Avatar answered Nov 19 '22 13:11

user1032613