Re: Getting Gravity from ICM-20948
by adafruit_support_mike on Tue Jun 08, 2021 7:57 pm
The device doesn’t calculate gravity for you, but you can get a good approximation by taking a running derivative of the acceleration vector.
Store a copy of the accelerometer values before taking a new reading, then subtract the old values from the new ones. Any difference between them represents a change in acceleration, which has to be the result of an external force.. the three differences are components of a vector proportional to the change in external force. A difference of zero (or near zero) indicates constant acceleration, which comes from two things: a constant external force, and gravity.
External forces have to stop eventually, and tend to drop off quickly for most kinds of motion. A running sum of the differences should be zero most of the time.
If you subtract the running sum from each new reading, you’ll get the gravity vector.
Running sums of digital readings tend to accumulate error over time, so you’ll want to get rid of any long-term nonzero values. An easy way to do that is to multiply the running sum by 0.95 each time you calculate a new value. Any constant offsets will fade to nothing in a reasonable time. You do lose some real information too, so you can adjust the multiplier value for the best compromise. Any value between 0 and 1 will work, with small multipliers dropping to zero quickly but losing a lot of real information, and larger numbers keeping most of the real information but letting errors hang around longer.