Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing Gravity from Accelerometer ... Documentation code

Tags:

android

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

In the above code what is gravity? What do I initialize it too?

like image 989
user678392 Avatar asked Dec 13 '25 03:12

user678392


1 Answers

With an accelerometer you always have a static acceleration reading of around 1g towards the earth. The above code is simply a low-pass filter to remove that static component over time. Each time a reading is taken it's using 80% of the existing gravity measurement combined with 20% of the new reading to keep track of that so that static component so it can be removed later.

Initialize the gravity array to values of zero for a start. However be aware that the reading won't be accurate until five samples have been taken. You might want to introduce a counter and ignore the readings until the filter has had a chance to stabilize.

Without that code if your device was laying flat on a table for example you'd get a constant reading of 1g on the Z-axis (for the most common accelerometer mounting arrangement). Using the code you should get a reading of close to zero and only see readings as you pick it up.

like image 118
PeterJ Avatar answered Dec 15 '25 16:12

PeterJ