Search code examples
androidaccelerometerandroid-sensorssensormanager

Android accelerometer filters


Trying to understand the official Android documentation for accelerometer sensor. It is stated there:

It should be apparent that in order to measure the real acceleration of the device, the contribution of the force of gravity must be eliminated. This can be achieved by applying a high-pass filter. Conversely, a low-pass filter can be used to isolate the force of gravity.

And the code for the filter is:

 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.8;

      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];
 }

Ok. Suppose I'm pushing the device in portrait orientation towards the sky with acceleration equal to 6 m / s^2. I think that in that case I should get something like [0, 15, 0] in event.values, right?

So, when I apply this filter for 20 points in Excel, it comes out that gravity tends to be equal to [0, 15, 0] and linear_acceleration aims to [0, 0, 0].

What am I missing?

P.S. I know about TYPE_GRAVITY, just trying to understand the math.

P.P.S. Also, why TYPE_GRAVITY sensor returns positive y value (+9.806) in portrait mode? Shouldn't it be -9.806 instead?


Solution

  • About TYPE_GRAVITY, think about it this way:

    You are sitting in box floating in space where there is no gravity. If a jet pushes you up (in +Y direction) with the acceleration of +9.8 upward. What you feel is a gravity of 9.8 downward. So technically the force that you feel due to gravity, is equivalent of a force in space where you are pushed up.

    That's why you get +9.8. But again, these are just how they are "defined". there was nothing wrong if they had defined gravity -9.8. All you need to do to make all parts of your math to be following the same rule. DO NOT change the convention...