I would like to detect using accelerometer if phone is moving up or down and how many times direction was changed.
I am using this code:
lastY = 0;
lastYChange = 0;
initialized = false;
...
if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) {
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
...
@Override
public void onSensorChanged(SensorEvent event) {
float y = event.values[1];
if (!initialized) {
lastY = y;
initialized = true;
}
else {
float yChange = lastY - y;
float deltaY = Math.abs(yChange);
if (deltaY < 2) {
deltaY = 0;
}
else {
if (lastYChange < 0 && yChange > 0) {
counter += 1;
textViewDirection.setText("Direction: Top");
textViewCounter.setText("Counter: " + counter);
}
else if (lastYChange > 0 && yChange < 0) {
counter += 1;
textViewDirection.setText("Direction: Bottom");
textViewCounter.setText("Counter: " + counter);
}
lastYChange = yChange;
}
lastY = y;
textViewAcceleration.setText("Acceleration is: " + deltaY);
}
}
So if I move phone in only one direction, for example top direction, counter
should be increased by only 1, and textViewDirection
should have value of "Direction: Top"
.
Instead, with this code counter is increased multiple times and textViewDirection
is switching from "Direction: Top"
and "Direction: Down"
.
Does anyone know to fix this? So that, for example, if I move phone up, then down, then up, counter
should have value of 3, and textViewDirection
should have value "Direction: Top"
, "Direction: Down"
and "Direction: Top"
, respectively.