I
I
Ivan Volodin2020-09-14 16:40:26
Android
Ivan Volodin, 2020-09-14 16:40:26

How to determine the slope of an Android phone in C# Xamarin?

How to get the tilt of an Android Smartphone in degrees (relative to any fixed position)?
I found the following article about a gyroscope explaining how to read the angular velocity from it, and wrote the following code, which should sum the angular velocity of the device to get its slope:

public float AngularVelocityX;
public float AngularVelocityY;
public float AngularVelocityZ;

public ValueShowViewModel()
{
    Gyroscope.Start(SensorSpeed.UI);
    Gyroscope.ReadingChanged += Gyroscope_ReadingChanged;
}

void Gyroscope_ReadingChanged(object sender, GyroscopeChangedEventArgs e)
{
    var data = e.Reading;

    AngularVelocityX += data.AngularVelocity.X;
    AngularVelocityY += data.AngularVelocity.Y;
    AngularVelocityZ += data.AngularVelocity.Z;
}

However, the more time the application works, the more inaccuracy accumulates in the AngularVelocity variables that store the sum , and this comes to their complete discrepancy with the angles measured earlier in the same position.

I tried to do the same with the accelerometer, but its values ​​​​did not respond to changes in rotation only horizontally.

Is there a way using C# to get the tilt of an Android device?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Volodin, 2020-09-17
@int_i

Janus74 was right.
I solved this problem not completely, by simply extracting the vector from the quanterion.
The orientation sensor returns the rotation quaternion of the device, converting which you can get rotation in Euler angles.
The transformations from this question and from this Wikipedia article do not work for me personally (I will be glad if someone shares a working option), so I just extracted its vector from the quanterion and multiplied it by 180.
The value is very approximate, but with very minimal errors.

Vector3 toEuler(Quaternion q)
{
    return new Vector3(q.X * 180, q.Y * 180, q.Z * 180);
}

An msdn article with an application using the Ori Sensor...
Solving the issue of obtaining a rotation on CodeRoad
Question on StackOverflow on the topic of transformations
Question on CodeRoad on the topic of transformations
Another transformation algorithm

J
Janus74, 2020-09-14
@Janus74

Xamarin.Essentials. OrientationSensor
lay nearby, didn't it?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question