Mohsin
Mohsin

Reputation: 1596

How to detect device orientation using sensor values?

Trying to detect the device orientation using sensors values with the help of two common sensors available in every smart phone Accelerometer & Gyroscope.

In my application, I'm using expo listeners to read values from sensors those are in the form of x,y,z.

  Expo.Accelerometer.addListener((results) => {

           console.log(results)
  })

Output

 Object {
    "x": 0.005248264875262976,
    "y": -0.10594243556261063,
    "z": 1.004819393157959,
  }

Now my question is how do I accurately convert those x,y,z values in the form of orientation angle. Is it possible or what without ejecting my application?

Gyroscope

Accelerometer

DeviceMotion

PS: I don't want to rotate my application layouts to check the phone orientation. In my scenario I have it locked in portrait mode. Just need a device angle 0,90,-90 also note my app only depends on expo.

Upvotes: 2

Views: 2168

Answers (1)

pyankoff
pyankoff

Reputation: 194

When your device is at rest, accelerometer data basically shows the direction of gravitation in your device's frame of reference. Your example output is equivalent to device laying horizontally on the table (gravity in the direction of z-axis).

If you just want the 0,90,-90 angle you can use the following formula (assuming user holds device vertically):

alpha = atan(x/y)/pi*360

More context on accelerometer: https://www.digikey.com/en/articles/techzone/2011/may/using-an-accelerometer-for-inclination-sensing

Upvotes: 3

Related Questions