Johann
Johann

Reputation: 29877

Accelerometer giving random values when device is at rest

When I run my code, the values returned by the accelerometer seem to be random and even if I pick up the device and rotate it around, there doesn't seem to be any dramatic change in values or so obvious indication that the device has changed from a rest position to a moving position. I copied the code from Google's site. Basically I am trying to see if the device has moved at all from a rest position. Solution should work on Android 2.2 and above if possible:

sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_FASTEST);

float[] gravity = new float[3];

@Override
public void onSensorChanged(SensorEvent event)
{
  try
  {
    final float alpha = 0.8f;
    float[] linear_acceleration = new float[3];

    // Isolate the force of gravity with the low-pass filter.
    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];

    // Remove the gravity contribution with the high-pass filter.
    linear_acceleration[0] = event.values[0] - gravity[0];
    linear_acceleration[1] = event.values[1] - gravity[1];
    linear_acceleration[2] = event.values[2] - gravity[2];
  }
  catch (Exception ex)
  {
  }
}

Upvotes: 0

Views: 2095

Answers (2)

Marcelo Cordini
Marcelo Cordini

Reputation: 166

  1. Have you tried Sensor.TYPE_LINEAR_ACCELERATION? This sensor returns acceleration force excluding gravity and you don't need to calculate it
  2. Sensors are too sensitives and there is a lot of noise. It is almost impossible to get 0,0,0 values. You need to exclude small values.

Upvotes: 0

Marek R
Marek R

Reputation: 37927

When you are coping solution from documentation do it with understanding.
gravity have to be a field of the class since you need store state of low-pass filter. gravity holds average values of accelerometer, fast changes are your linear acceleration.

Upvotes: 1

Related Questions