50

I want to build an app that calculates accurate Distance travelled by iPhone (not long distance) using Gyro+Accelerometer. No need for GPS here.

How should I approach this problem?

7 Answers 7

84

Basic calculus behind this problem is in the expression

enter image description here

(and similar expressions for displacements in y and z) and basic geometry is the Pythagorean theorem

enter image description here

So, once you have your accelerometer signals passed through a low-pass filter and binned in time with sampling interval dt, you can find the displacement in x as (pardon my C...)

float dx=0.0f;
float vx=0.0f;
for (int i=1; i<n; i++)
 {
   vx+=(acceleration_x[i-1] + acceleration_x[i])/2.0f*dt;
   dx+=vx*dt;
 }

and similarly for dy and dz. Here

float acceleration_x[n];

contains x-acceleration values from start to end of measurement at times 0, dt, 2*dt, 3*dt, ... (n-1)*dt.

To find the total displacement, you just do

dl=sqrt(dx*dx + dy*dy + dz*dz);

Gyroscope is not necessary for this, but if you are measuring linear distances, you can use the gyroscope reading to control that rotation of the device was not too large. If rotation was too strong, make the user re-do the measurement.

5
  • 1
    Nice. I just saw that the questioner has never cast a vote nor accepted an answer, so +1 from me :-) In practice I ran into trouble after a few seconds because of error propagation even with Simpson rule for integration.
    – Kay
    Jul 11, 2011 at 9:16
  • Thanks Kay, I had a suspicion that the devil is in the details, I am sure that it is not impossible to fix. Off the top of my head, accelerometer's response may be nonlinear in amplitude at high frequencies, or they may not be subtracting gravity accurately enough. In both cases, filtering out problem frequencies (probably, everything above 30 Hz must be suppressed) and runtime calibration (hold still for 1 second and measure drift to compensate for it) should help. I guess I have to try it on my Android now.
    – drlemon
    Jul 11, 2011 at 22:44
  • It's still an unresolved problem to get accurate results i.e. something you can really use for a game or whatever. Like Ali said David Sachs has done some very research on Android (s. Ali's link to its Google Tech Talk). You might find useful ideas in the link I provided in my answer below. Be prepared to do some heavy maths (Kalman filter and derivatives).
    – Kay
    Jul 12, 2011 at 8:21
  • @drlemon : why are you doing - (acc_x[i-1]+acc_x[i])/2?
    – Ashwin
    Oct 22, 2012 at 6:08
  • @drlemon : shouldn't this be more accurate? stackoverflow.com/questions/12926459/…
    – Ashwin
    Oct 22, 2012 at 6:08
47

You get position by integrating the linear acceleration twice but the error is horrible. It is useless in practice.

Here is an explanation why (Google Tech Talk) at 23:20. I highly recommend this video.

Similar questions:


Update (24 Feb 2013): @Simon Yes, if you know more about the movement, for example a person walking and the sensor is on his foot, then you can do a lot more. These are called

     domain specific assumptions.

They break miserably if the assumptions do not hold and can be quite cumbersome to implement. Nevertheless, if they work, you can do fun things. See the links in my answer Android accelerometer accuracy (Inertial navigation) at indoor positioning.

27
  • Do you know if anyone has tried to find the source of the horrible systematic errors? Does suppressing high frequencies or pre-measurement calibration help?
    – drlemon
    Jul 11, 2011 at 22:45
  • Watch the video from 23:20, the Google Tech Talk I linked in my answer. It explains why you get that horrible error. Neither filtering nor calibration will help.
    – Ali
    Jul 12, 2011 at 0:54
  • 2
    I don't think they explain anything. He says "There are some ways to improve the linear movement estimate... but any kind of orientation errors are really important, all sorts of error couple in, including things like the cross axis error between the accelerometer and the gyroscope". To me, it looks like they just don't know what is going on, because if they did, they could suggest something to make the results better. Thanks for the video, very informative! I'll have to play with that accelerometer now when I have time.
    – drlemon
    Jul 12, 2011 at 16:54
  • is there any other way to do it precisely? What kind of other electronical devices could be used to get precise measurement?
    – Simon
    Dec 28, 2012 at 11:42
  • @Simon Depending on your application you may find my answer helpful (pedometer or RSSI-based localization). The source of the inaccuracy is the white noise of the gyros; with a ring laser gyro (1 pound plus batteries :) ) you can achieve better accuracy and that's what they do on airplanes.
    – Ali
    Dec 28, 2012 at 12:36
5

You should use the Core Motion interface like described in Simple iPhone motion detect. Especially all rotations can be tracked very accurately. If you plan to do something related to linear movements this is very hard stuff. Have a look at Getting displacement from accelerometer data with Core Motion.

3
  • Upvoted. It's amazing how many times this question pops up and people keep re-inventing the wheel in the shape of a square... :(
    – Ali
    Jan 29, 2012 at 9:15
  • @Ali Yes, I plan to write a blog article within the next months about clearing this up and publishing my results (didn't find the solution but some nice workaround) and then post an abstract as FAQ here at SO. Off-topic: I don't know how to contact you by this chat thing :( Are you doing iPhone programming as well? I've got a request (via SO :) for contracting (Prague) but I am busy. Drop me an email via my web-site if you are interested. BTW: Congrats for hitting 2k rep :)))
    – Kay
    Jan 29, 2012 at 9:59
  • Thanks :) I just dropped you and e-mail, so you will have my e-mail address for future reference. I was also thinking about writing an article clearing this mess up. Unfortunately, I do not have the time to do so. :( Anyhow, please inform me when you are done with yours, so I can tell people about it!
    – Ali
    Jan 29, 2012 at 10:20
1

I took a crack at this and gave up (late at night, didn't seem to be getting anywhere). This is for a Unity3d project.

If anyone wants to pick up where I left off, I would be happy to elaborate on what all this stuff does.

Basically after some of what turned out to be false positives, I thought I'd try and filter this using a low pass filter, then attempted to remove bounces by finding a trend, then (acc_x[i-1]+acc_x[i])/2.

It looks like the false positive is still coming from the tilt, which I attempted to remove..

If this code is useful or leads you someplace, please let me know!

using UnityEngine;
using System.Collections.Generic;

/// <summary>
/// rbi.noli@gmail.com
/// </summary>
public class AccelerometerInput : MonoBehaviour 
{

    Transform myTransform;
    Gyroscope gyro;
    GyroCam gyroCam;

    void Awake()
    {
        gyroCam= FindObjectOfType<GyroCam> ();
        myTransform = transform;
        if (SystemInfo.supportsGyroscope) {
            gyro = Input.gyro;
            gyro.enabled = true;
        }
    }

    bool shouldBeInitialized = false; 
    void Update () 
    {

        transform.Translate (GetAccelerometer ());// * Time.deltaTime * speed);

        //GetComponent<Rigidbody> ().AddForce (GetAccelerometer ());

    }

    public float speed = 10.0F;

    public Vector3 dir;
    public float f;
    Vector3 GetAccelerometer()
    {

        dir = Input.acceleration;

        dir.x *= gyro.attitude.x;
        dir.z *= gyro.attitude.z;

        if (Mathf.Abs (dir.x) < .001f)
            dir.x = 0;
        dir.y = 0;
        if (Mathf.Abs (dir.z) < .001f)
            dir.z = 0;

        RecordPointsForFilter (dir);

        //print ("Direction : " + dir.ToString("F7"));

        return TestPointsForVelocity();
    }

    Vector3[] points = new Vector3[20];
    int index;
    void RecordPointsForFilter(Vector3 recentPoint)
    {
        if (index >= 20)
            index = 0;
        points [index] = EvaluateTrend (recentPoint);;
        index++;
    }

    //try to remove bounces
    float xTrend = 0;
    float zTrend = 0;
    float lastTrendyX = 0;
    float lastTrendyZ = 0;
    Vector3 EvaluateTrend(Vector3 recentPoint)
    {

        //if the last few points were positive, and this point is negative, don't pass it along
        //accumulate points into a trend
        if (recentPoint.x > 0)
            xTrend += .01f;
        else
            xTrend -= .1f;

        if (recentPoint.z > 0)
            zTrend += .1f;
        else
            zTrend -= .1f;

        //if point matches trend, keep it
        if (xTrend > 0) {
            if (recentPoint.x > 0)
                lastTrendyX = recentPoint.x;
        } else  // xTrend < 0
            if (recentPoint.x < 0)
            lastTrendyX = recentPoint.x;

        if (zTrend > 0) {
            if (recentPoint.z > 0)
                lastTrendyZ = recentPoint.z;
        } else  // xTrend < 0
            if (recentPoint.z < 0)
                lastTrendyZ = recentPoint.z;

        return new Vector3( lastTrendyX, 0, lastTrendyZ);
    }

    Vector3 TestPointsForVelocity()
    {
        float x = 0;
        float z = 0;

        float xAcc = 0;
        float zAcc = 0;

        int successfulHits = 0;
        for(int i = 0; i < points.Length; i++)
        {
            if(points[i]!=null)
            {
                successfulHits ++;
                xAcc += points[i].x;
                zAcc += points[i].z;
            }
        }

        x = xAcc / successfulHits;
        z = zAcc / successfulHits;

        return new Vector3 (x, 0, z);

    }
}
0

(acc_x[i-1]+acc_x[i])/2 is a low pass filter, it is the mean value between two measures in time

also look at here : http://www.freescale.com/files/sensors/doc/app_note/AN3397.pdf pag :3

0

Navisens.

https://navisens.com/#how-work

Here the claim - Navisens patent-pending technology processes accelerometer and gyroscope data in a unique way to locate your phone.

Tried out the demo application, which works mostly in mapping the movements with out Location Services or WiFi once the inital location & direction are set.

iOS SDK - https://github.com/navisens/iOS-SDK

Android SDK - https://github.com/navisens/Android-SDK

Note: This is not open source

-1

Here is the answer. Somebody asked before.

There is an app called RangeFinder doing the same thing ( available in App Store ) .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.