user2060617
user2060617

Reputation: 79

getting angle using gyroscope in android

Can I calculate the angle from gyroscope with this code? I mean is the calculation of dT correct?

public void onSensorChanged(SensorEvent event) {
            switch (event.sensor.getType()) {
      /* Other sensor cases */
           case Sensor.TYPE_GYROSCOPE: 
            for (int j=0;j<3;j++) mGyro[j] = event.values[j];
            if(i==0)
                i=1;
            else
                i=2;
            if(i==1)
                start=System.nanoTime();
                else if(i==2) {
                    finish=System.nanoTime();
                 dT=( finish-start )/1000000000f;
                             i=0;
                }

            angle[0]=(float) ((angle[0]+mGyro[0]*dT)*180/3.1428f);
            angle[1]=(float) ((angle[1]+mGyro[0]*dT)*180/3.1428f);
            angle[2]=(float) ((angle[2]+mGyro[0]*dT)*180/3.1428f);

            break;

Upvotes: 1

Views: 13294

Answers (2)

Ali
Ali

Reputation: 58461

I assume you are trying to get the orientation. No, those formulas are not correct, this is not how you integrate the angular rates in 3D, that is a bit tricky actually.

If you want angles then just use SensorManager.getOrientation() from the API. In other words, somebody has already written this code for you, there is no need to re-invent the wheel.

Do not use yaw, pitch and roll for arbitrary orientations, Euler angles are evil.

If your goal is to learn, you can find how the integration in 3D in Direction Cosine Matrix IMU: Theory manuscript. This manuscript is basically a tutorial, pretty straightforward and simple.

Upvotes: 2

Alexander Pacha
Alexander Pacha

Reputation: 9710

The documentation of the SensorEvent class gives a full example of how to use the gyroscope. You basically only have to copy and paste the code. See this answer on how to get an orientation from the gyroscope.

Upvotes: 0

Related Questions