0

I want to trigger some function when the phone is tilted back and forth along the YZ axis. If you were holding your phone in front of your face, you'd be tilting it back until it's nearly parallel with the floor, then back up until it's perpendicular to the floor. Looking at the drawing below, it would be the pitch.

enter image description here

I've tried to do so by only looking at the Z value of the accelerometer. Detecting a change in Z should theoretically be enough to detect a change in pitch, but in practice it is wildly erratic based on the sampling rate and the threshold for the change. Someone tilting the phone back and forth quickly will have a different result than someone doing so slowly. How do I make it so I'm not reliant on the sampling rate and the threshold for the tilt?

@Override
public void onSensorChanged(SensorEvent event) {
    newZ = event.values[2];

    if (Math.abs(oldZ - newZ) > 3) {

        //do something
    }

    oldZ = newZ;
}
PerracoLabs
  • 16,449
  • 15
  • 74
  • 127
  • the noise in the accelerometer readings can be reduced with a low pass filter check this out https://www.built.io/blog/applying-low-pass-filter-to-android-sensor-s-readings – JRowan Sep 12 '19 at 17:48
  • It sounds like you're looking for the orientation without the acceleration. You may want to look into using Sensor Manager's [getOrientation](https://developer.android.com/guide/topics/sensors/sensors_position#sensors-pos-orient) or you could try monitoring the axis using the [Gravity Sensor](https://developer.android.com/guide/topics/sensors/sensors_motion.html) – Sammy T Sep 12 '19 at 20:01

1 Answers1

1

You cannot use the z-value to detect the titling since the accelerometer value is given in term of device coordinate. You should use the change of inclinations instead (see How to measure the tilt of the phone in XY plane using accelerometer in Android)

Hoan Nguyen
  • 18,033
  • 3
  • 50
  • 54