Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read x y z coordinates of android phone using accelerometer

I am going to develop Android application which needs to read x,y,z coordinates of phone on 3D space.

I would like to write a simple code and test on the device..

I am using ginger bread on both the device and emulator.

like image 835
Ruwantha Avatar asked Jun 17 '12 03:06

Ruwantha


People also ask

What does XYZ mean in an accelerometer?

The accelerometer in the mobile device provides the XYZ coordinate values, which is used to measure the position and the acceleration of the device. The XYZ coordinate represents direction and position of the device at which acceleration occurred.

How can I get sensor data in Android?

You can access sensors available on the device and acquire raw sensor data by using the Android sensor framework. The sensor framework provides several classes and interfaces that help you perform a wide variety of sensor-related tasks.


1 Answers

To get position from acceleration you need to integrate it twice.

Integrating acceleration gives you velocity and integrating the velocity gives you the position.

Keep in mind that integrating noise creates drift and integrating drift creates A LOT of drift, the android sensors tend to generate quite a lot of noise.

On my Galaxy S3 I have been able to get the drift in position down to 0.02 m in 5 seconds using Google's Linear Accelerometer composite sensor.

I am not sure if you can use the linear accelerometer sensor on gingerbread. If you can't you will have to remove the gravity before integrating.

If you haven't already, read everything here http://developer.android.com/guide/topics/sensors/sensors_motion.html

A great talk about the motion sensors in android

http://www.youtube.com/watch?v=C7JQ7Rpwn2k

Code:

static final float NS2S = 1.0f / 1000000000.0f;
float[] last_values = null;
float[] velocity = null;
float[] position = null;
long last_timestamp = 0;

@Override
public void onSensorChanged(SensorEvent event) {
    if(last_values != null){
        float dt = (event.timestamp - last_timestamp) * NS2S;

        for(int index = 0; index < 3;++index){
            velocity[index] += (event.values[index] + last_values[index])/2 * dt;
            position[index] += velocity[index] * dt;
        }
    }
    else{
        last_values = new float[3];
        velocity = new float[3];
        position = new float[3];
        velocity[0] = velocity[1] = velocity[2] = 0f;
        position[0] = position[1] = position[2] = 0f;
    }
    System.arraycopy(event.values, 0, last_values, 0, 3);
    last_timestamp = event.timestamp;
}

Now you have the position in 3d space, keep in mind it assumes that the phone is stationary when it starts sampling.

If you don't remove gravity it will soon be very far away.

This doesn't filter the data at all and will generate a lot of drift.

like image 100
spontus Avatar answered Sep 18 '22 23:09

spontus