Example usage for android.hardware SensorManager getOrientation

List of usage examples for android.hardware SensorManager getOrientation

Introduction

In this page you can find the example usage for android.hardware SensorManager getOrientation.

Prototype

public static float[] getOrientation(float[] R, float[] values) 

Source Link

Document

Computes the device's orientation based on the rotation matrix.

Usage

From source file:com.example.casthelloworld.MainActivity.java

@Override
public void onSensorChanged(SensorEvent sensorEvent) {

    if (sensorEvent.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE) {
        return;/*from  w  w  w  .ja  v a2s  . c  o  m*/
    }

    SensorManager.getRotationMatrixFromVector(mRotationMatrix, sensorEvent.values);

    SensorManager.remapCoordinateSystem(mRotationMatrix, SensorManager.AXIS_X, SensorManager.AXIS_Z,
            mRotationMatrix);

    SensorManager.getOrientation(mRotationMatrix, orientationVals);

    orientationVals[2] = (float) Math.toDegrees(orientationVals[2]);

    float Roll = orientationVals[2];

    if (Roll < -85 && Roll > -95 && lastVal != 0.0f) {
        // Log.d("Middle: ", "" + Roll);
        lastVal = 0.0f;
        try {
            directionMessage.put("direction", (double) lastVal);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mGameManagerClient.sendGameMessage(directionMessage);
    } else if (Roll <= -95 && Roll > -105 && lastVal != -0.2f) {
        // Log.d("Left", "" + Roll);
        lastVal = -0.2f;
        try {
            directionMessage.put("direction", (double) lastVal);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mGameManagerClient.sendGameMessage(directionMessage);
    } else if (Roll >= -85 && Roll < -75 && lastVal != 0.2f) {
        // Log.d("Right", "" + Roll);
        lastVal = 0.2f;
        try {
            directionMessage.put("direction", (double) lastVal);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mGameManagerClient.sendGameMessage(directionMessage);
    } else if (Roll <= -105 && Roll > -115 && lastVal != -0.4f) {
        // Log.d("Left", "" + Roll);
        lastVal = -0.4f;
        try {
            directionMessage.put("direction", (double) lastVal);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mGameManagerClient.sendGameMessage(directionMessage);
    } else if (Roll >= -75 && Roll < -65 && lastVal != 0.4f) {
        // Log.d("Right", "" + Roll);
        lastVal = 0.4f;
        try {
            directionMessage.put("direction", (double) lastVal);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mGameManagerClient.sendGameMessage(directionMessage);
    } else if (Roll <= -115 && Roll > -125 && lastVal != -0.6f) {
        // Log.d("Left", "" + Roll);
        lastVal = -0.6f;
        try {
            directionMessage.put("direction", (double) lastVal);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mGameManagerClient.sendGameMessage(directionMessage);
    } else if (Roll >= -65 && Roll < -55 && lastVal != 0.6f) {
        // Log.d("Right", "" + Roll);
        lastVal = 0.6f;
        try {
            directionMessage.put("direction", (double) lastVal);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mGameManagerClient.sendGameMessage(directionMessage);
    } else if (Roll <= -125 && Roll > -135 && lastVal != -0.8f) {
        // Log.d("Left", "" + Roll);
        lastVal = -0.8f;
        try {
            directionMessage.put("direction", (double) lastVal);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mGameManagerClient.sendGameMessage(directionMessage);
    } else if (Roll >= -55 && Roll < -45 && lastVal != 0.8f) {
        // Log.d("Right", "" + Roll);
        lastVal = 0.8f;
        try {
            directionMessage.put("direction", (double) lastVal);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mGameManagerClient.sendGameMessage(directionMessage);
    } else if (Roll <= -135 && lastVal != -1.0f && lastVal != 1.0f) {
        // Log.d("Left", "" + Roll);
        lastVal = -1.0f;
        try {
            directionMessage.put("direction", (double) lastVal);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mGameManagerClient.sendGameMessage(directionMessage);
    } else if (Roll >= -45 && lastVal != 1.0f && lastVal != -1.0f) {
        // Log.d("Right", "" + Roll);
        lastVal = 1.0f;
        try {
            directionMessage.put("direction", (double) lastVal);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mGameManagerClient.sendGameMessage(directionMessage);
    }

}

From source file:jp.co.recruit_lifestyle.android.widget.BeerSwipeRefreshLayout.java

@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() != Sensor.TYPE_ROTATION_VECTOR || !mBeerView.isMax()) {
        return;/*from   w w w .j  av  a  2 s  .  com*/
    }

    float[] rotationMatrix = new float[9];
    SensorManager.getRotationMatrixFromVector(rotationMatrix, event.values);

    float[] adjustedRotationMatrix = new float[9];
    SensorManager.remapCoordinateSystem(rotationMatrix, SensorManager.AXIS_X, SensorManager.AXIS_Z,
            adjustedRotationMatrix);

    float[] orientation = new float[3];
    SensorManager.getOrientation(adjustedRotationMatrix, orientation);

    float roll = orientation[2] * -57;

    if (roll < ROLL_LIMIT && roll > -ROLL_LIMIT) {
        mBeerView.drawGlass(-roll);
        mBeerView.drawGlassFroth(-roll, 1);
        mOldRoll = -roll;
    } else {
        mBeerView.drawGlass(mOldRoll);
        mBeerView.drawGlassFroth(mOldRoll, 1);
    }
}

From source file:com.example.basensortracker.SensorFusionActivity.java

public void gyroFunction(SensorEvent event) {
    // don't start until first accelerometer/magnetometer orientation has
    // been acquired
    if (accMagOrientation == null)
        return;//from   w w w . ja  v a 2s.  c  om

    // initialisation of the gyroscope based rotation matrix
    if (initState) {
        float[] initMatrix = new float[9];
        initMatrix = getRotationMatrixFromOrientation(accMagOrientation);
        float[] test = new float[3];
        SensorManager.getOrientation(initMatrix, test);
        gyroMatrix = matrixMultiplication(gyroMatrix, initMatrix);
        initState = false;
    }

    // copy the new gyro values into the gyro array
    // convert the raw gyro data into a rotation vector
    float[] deltaVector = new float[4];
    if (timestamp != 0) {
        final float dT = (event.timestamp - timestamp) * NS2S;
        System.arraycopy(event.values, 0, gyro, 0, 3);
        getRotationVectorFromGyro(gyro, deltaVector, dT / 2.0f);
    }

    // measurement done, save current time for next interval
    timestamp = event.timestamp;

    // convert rotation vector into rotation matrix
    float[] deltaMatrix = new float[9];
    SensorManager.getRotationMatrixFromVector(deltaMatrix, deltaVector);

    // apply the new rotation interval on the gyroscope based rotation
    // matrix
    gyroMatrix = matrixMultiplication(gyroMatrix, deltaMatrix);

    // get the gyroscope based orientation from the rotation matrix
    SensorManager.getOrientation(gyroMatrix, gyroOrientation);
}

From source file:com.example.android.camera2video.CameraActivity.java

@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        logText("ACCELEROMETER," + event.values[0] + "," + event.values[1] + "," + event.values[2]);
        mAccVal = event.values;/*from w w  w .ja  v a  2 s.c  o m*/
    } else if (event.sensor.getType() == Sensor.TYPE_GRAVITY) {
        logText("GRAVITY," + event.values[0] + "," + event.values[1] + "," + event.values[2]);
    } else if (event.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) {
        logText("LINEAR_ACCELERATION," + event.values[0] + "," + event.values[1] + "," + event.values[2]);
    } else if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
        logText("GYROSCOPE," + event.values[0] + "," + event.values[1] + "," + event.values[2]);
    } else if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE_UNCALIBRATED) {
        logText("GYROSCOPE_UNCALIBRATED," + event.values[0] + "," + event.values[1] + "," + event.values[2]
                + "," + event.values[3] + "," + event.values[4] + "," + event.values[5]);
    } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
        logText("MAGNETIC_FIELD," + event.values[0] + "," + event.values[1] + "," + event.values[2]);
        mMagVal = event.values;
        if (mAccVal != null) {
            float R[] = new float[9];
            float I[] = new float[9];
            boolean success = SensorManager.getRotationMatrix(R, I, mAccVal, mMagVal);
            if (success) {
                float orientation[] = new float[3];
                SensorManager.getOrientation(R, orientation);
                logText("ORIENTATION," + orientation[0] + "," + orientation[1] + "," + orientation[2]); //azimuth, pitch and roll
            }
        }
    }
}

From source file:com.bolatu.gezkoncsvlogger.GyroOrientation.ImuOCfQuaternion.java

/**
 * Calculate the fused orientation.// www  . j ava  2s. c o  m
 */
private void calculateFusedOrientation() {
    float oneMinusCoeff = (1.0f - filterCoefficient);

    // Apply the complementary filter. // We multiply each rotation by their
    // coefficients (scalar matrices)...

    // Scale our quaternion for the gyroscope
    quatGyro = quatGyro.multiply(filterCoefficient);

    // Scale our quaternion for the accel/mag
    quatAccelMag = quatAccelMag.multiply(1 - oneMinusCoeff);

    // ...and then add the two quaternions together.
    // output[0] = alpha * output[0] + (1 - alpha) * input[0];
    quatGyro = quatGyro.add(quatAccelMag);

    // Now we get a structure we can pass to get a rotation matrix, and then
    // an orientation vector from Android.
    qvFusedOrientation[0] = (float) quatGyro.getVectorPart()[0];
    qvFusedOrientation[1] = (float) quatGyro.getVectorPart()[1];
    qvFusedOrientation[2] = (float) quatGyro.getVectorPart()[2];
    qvFusedOrientation[3] = (float) quatGyro.getScalarPart();

    // We need a rotation matrix so we can get the orientation vector...
    // Getting Euler angles from a quaternion is not trivial, so this is the
    // easiest way, but perhaps not the fastest way of doing this.
    SensorManager.getRotationMatrixFromVector(rmFusedOrientation, qvFusedOrientation);

    // Get the fused orienatation
    SensorManager.getOrientation(rmFusedOrientation, vFusedOrientation);
}

From source file:net.line2soft.preambul.controllers.SlippyMapListener.java

@Override
public void onSensorChanged(SensorEvent event) {
    CompassView cp = (CompassView) activity.findViewById(R.id.compass);
    CompassView cpBig = (CompassView) activity.findViewById(R.id.compassBig);
    switch (event.sensor.getType()) {
    case Sensor.TYPE_ACCELEROMETER:
        System.arraycopy(event.values, 0, mGravity, 0, 3);
        break;/*from  ww  w  . j ava2 s .co  m*/
    case Sensor.TYPE_MAGNETIC_FIELD:
        System.arraycopy(event.values, 0, mMagnetic, 0, 3);
        break;
    default:
        return;
    }
    if (SensorManager.getRotationMatrix(mRotationM, null, mGravity, mMagnetic)) {
        SensorManager.remapCoordinateSystem(mRotationM, SensorManager.AXIS_X, SensorManager.AXIS_Z,
                mRemapedRotationM);
        SensorManager.getOrientation(mRemapedRotationM, mOrientation);
        int mAzimuth = (int) Math.round((Math.toDegrees(mOrientation[0])) * 2) / 2;
        cp.updateDirection(mAzimuth);
        cpBig.updateDirection(mAzimuth);
    }
}

From source file:com.javadog.cgeowear.cgeoWear.java

/**
 * Interprets watch compass if user has requested that feature.
 *///www  .j  ava 2s. c om
@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        gravity = event.values.clone();
    } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
        geomagnetic = event.values.clone(); //TODO: Some watches don't let me access the compass correctly yet.
    }

    if (gravity != null && geomagnetic != null) {
        float[] R = new float[9];
        float[] I = new float[9];

        boolean success = SensorManager.getRotationMatrix(R, I, gravity, geomagnetic);
        if (success) {
            float[] orientation = new float[3];
            SensorManager.getOrientation(R, orientation);
            float azimuth = (float) Math.toDegrees(orientation[0]);

            if (currentLocation != null) {
                float smoothedLatitude = smoothSensorValues(oldLatitude, (float) currentLocation.getLatitude(),
                        1 / 3f);
                float smoothedLongitude = smoothSensorValues(oldLongitude,
                        (float) currentLocation.getLongitude(), 1 / 3f);
                float smoothedAltitude = smoothSensorValues(oldAltitude, (float) currentLocation.getAltitude(),
                        1 / 3f);

                GeomagneticField geomagneticField = new GeomagneticField(smoothedLatitude, smoothedLongitude,
                        smoothedAltitude, System.currentTimeMillis());
                azimuth += geomagneticField.getDeclination();

                float bearing = currentLocation.bearingTo(geocacheLocation);

                direction = smoothSensorValues(oldDirection, -(azimuth - bearing), 1 / 5f);

                //Set old values to current values (for smoothing)
                oldDirection = direction;
                oldLatitude = smoothedLatitude;
                oldLongitude = smoothedLongitude;
                oldAltitude = smoothedAltitude;

                //Display direction on compass if update interval has passed
                long currentTime = System.currentTimeMillis();
                if ((currentTime - prevTime) > DIRECTION_UPDATE_SPEED) {
                    rotateCompass(direction);
                    prevTime = currentTime;
                }
            }
        }
    }
}

From source file:com.tritop.androsense2.fragments.GpsFragment.java

@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        mAccel = event.values;/*from  w  w w.ja v a  2 s .c om*/
    }
    if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
        mMag = event.values;
    }
    if ((mAccel != null) && (mMag != null)) {
        float R[] = new float[9];
        float I[] = new float[9];
        float Rot[] = new float[9];
        if (SensorManager.getRotationMatrix(R, I, mAccel, mMag)) {
            float orientation[] = new float[3];
            int axisX = 0, axisY = 0;
            switch (display.getRotation()) {
            case Surface.ROTATION_0:
                axisX = SensorManager.AXIS_X;
                axisY = SensorManager.AXIS_Y;
                break;
            case Surface.ROTATION_90:
                axisX = SensorManager.AXIS_Y;
                axisY = SensorManager.AXIS_MINUS_X;
                break;
            case Surface.ROTATION_180:
                axisX = SensorManager.AXIS_MINUS_X;
                axisY = SensorManager.AXIS_MINUS_Y;
                break;
            case Surface.ROTATION_270:
                axisX = SensorManager.AXIS_MINUS_Y;
                axisY = SensorManager.AXIS_X;
                break;
            default:
                break;
            }

            SensorManager.remapCoordinateSystem(R, axisX, axisY, Rot);
            SensorManager.getOrientation(Rot, orientation);
            aRotation = orientation[0];
            aRotation = (int) Math.toDegrees(aRotation);
            satView.setAzimutRotation(-aRotation);
            satView.invalidate();
        }
    }
}

From source file:com.samebits.beacon.locator.ui.view.RadarScanView.java

private synchronized void calcBearing(SensorEvent event) {

    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        System.arraycopy(event.values, 0, mLastAccelerometer, 0, event.values.length);
        mLastAccelerometerSet = true;//  www .  j  av  a2  s  .  co m
    } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
        System.arraycopy(event.values, 0, mLastMagnetometer, 0, event.values.length);
        mLastMagnetometerSet = true;
    }
    if (mLastAccelerometerSet && mLastMagnetometerSet) {

        /* Create rotation Matrix */
        float[] rotationMatrix = new float[9];
        if (SensorManager.getRotationMatrix(rotationMatrix, null, mLastAccelerometer, mLastMagnetometer)) {
            SensorManager.getOrientation(rotationMatrix, mOrientation);

            float azimuthInRadians = mOrientation[0];

            angleLowpassFilter.add(azimuthInRadians);

            mLast_bearing = (float) (Math.toDegrees(angleLowpassFilter.average()) + 360) % 360;

            postInvalidate();

            //Log.d(Constants.TAG, "orientation bearing: " + mLast_bearing);

        }
    }
}

From source file:com.cubic9.android.droidglove.Main.java

@Override
public void onSensorChanged(SensorEvent event) {
    Float[] avgAngles = new Float[3];
    float[] rotationMatrix = new float[9];
    float[] attitude = new float[3];

    switch (event.sensor.getType()) {
    case Sensor.TYPE_MAGNETIC_FIELD:
        geomagnetic = event.values.clone();
        break;/*from   ww w.j  av  a  2 s  .  c om*/
    case Sensor.TYPE_ACCELEROMETER:
        gravity = event.values.clone();
        break;
    }

    if (geomagnetic != null && gravity != null) {
        SensorManager.getRotationMatrix(rotationMatrix, null, gravity, geomagnetic);
        SensorManager.getOrientation(rotationMatrix, attitude);

        if (!mInitirizedSensor) {
            if (mCountBeforeInit > 20) {
                mInitirizedSensor = true;
                initYaw = (float) Math.toDegrees(attitude[0]);
            } else {
                mCountBeforeInit++;
            }
        }

        for (int i = 0; i < 3; i++) {
            for (int j = AVERAGE_AMOUNT - 1; j > 0; j--) {
                mOrigAngles[i][j] = mOrigAngles[i][j - 1];
            }
        }

        mOrigAngles[0][0] = (float) Math.toDegrees(attitude[0]) - initYaw;
        mOrigAngles[1][0] = (float) Math.toDegrees(attitude[1]);
        mOrigAngles[2][0] = (float) Math.toDegrees(attitude[2]);

        for (int i = 0; i < 3; i++) {
            avgAngles[i] = 0f;
            for (int j = 0; j < AVERAGE_AMOUNT; j++) {
                avgAngles[i] += mOrigAngles[i][j];
            }
            avgAngles[i] /= AVERAGE_AMOUNT;
        }

        /*
         * textViewX.setText(avgAngles[0].toString());
         * textViewY.setText(avgAngles[1].toString());
         * textViewZ.setText(avgAngles[2].toString());
         * textViewGrip.setText(Float.toString(mYDiff));
         */

        // create message for send
        List<Object> valueList = new ArrayList<Object>();
        valueList.add(avgAngles[1]);
        valueList.add(avgAngles[0]);
        valueList.add(-avgAngles[2]);
        valueList.add(Integer.valueOf((int) mYDiff));
        OSCMessage message = new OSCMessage(OSC_ADDRESS_TO_PC, valueList);

        // send
        try {
            mSender.send(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}