I'm trying to write a small app which updates the screen with the speed of the phone. It uses the accelerometer to calculate the current speed and writes it on the screen. The problem is that the velocity doesn't go back to zero speed after moving the phone. It will sort of stabilize at the top point the velocity had. I'm using the LINEAR_ACCELEROMETER
This is the code:
public class AccelerometerUpSensor extends SensorAbstract{
private ExerciseFragment fragment;
private double v0 = 0;
private float lastX;
private float lastY;
private float lastZ;
private long interval;
private long lastEvent = System.currentTimeMillis();
public AccelerometerUpSensor(SensorManager sensorManager, ExerciseFragment fragment, int[] sensorTypes){
super(sensorManager,sensorTypes);
this.fragment = fragment;
}
@Override
public final void onSensorChanged(SensorEvent event) {
lastX = event.values[0];
lastY = event.values[1];
lastZ = event.values[2];
long now = System.currentTimeMillis();
interval = (now - lastEvent);
lastEvent = now;
double acceleration = lastX+lastY+lastZ;
double velocity = v0 + (acceleration*(interval/(double)1000));
v0 = velocity;
System.out.println(velocity);
}
private void calculateVelocity(float x, float y, float z){
long now = System.currentTimeMillis();
interval = (now - lastEvent);
if(interval > 100){
lastEvent = now;
double acceleration = x+y+z-lastX-lastY-lastZ;
double velocity = v0 + (acceleration*(interval/(double)1000));
velocities.add(Math.abs(velocity));
v0= velocity;
lastX = x;
lastY = y;
lastZ = z;
}
}
This is the code I used to calculate the velocity per 100 millisecond. The velocities-array is used to calculate an average velocity each second, which you can ignore. Input for the method is the event.values