0

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.

msor
  • 5
  • 5
  • 1
    this answer your question I guess https://stackoverflow.com/questions/39884057/is-it-possible-to-measure-the-how-far-the-phone-travels-vertically – Maytham Fahmi Dec 10 '17 at 19:59
  • @maytham-ɯɐɥʇʎɐɯ If you feel the question is answered by another question, then it's helpful to vote-to-close as a duplicate of that question. – Makyen Dec 10 '17 at 20:41
  • Possible duplicate of [Is it possible to measure the how far the phone travels vertically](https://stackoverflow.com/questions/39884057/is-it-possible-to-measure-the-how-far-the-phone-travels-vertically) – Maytham Fahmi Dec 11 '17 at 06:30

1 Answers1

0

This is a possible accelerometer result when you move the sensor Unfortunately, y accelerometer waveform is not as straightforward to behave as you thought in your code. It oscillates a lot, e.g. when you stop the device