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