0

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)
  {
  }
}
Johann
  • 27,536
  • 39
  • 165
  • 279
  • gravity should be a field of class not variable in method! – Marek R Feb 19 '13 at 08:44
  • Doesn't make any difference. The raw values in event don't have any significant change between rest and moving. I removed the gravity array above though. – Johann Feb 19 '13 at 09:09

2 Answers2

1

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.

Marek R
  • 32,568
  • 6
  • 55
  • 140
0
  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.
Marcelo Cordini
  • 166
  • 1
  • 7