Example usage for android.hardware SensorManager getRotationMatrix

List of usage examples for android.hardware SensorManager getRotationMatrix

Introduction

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

Prototype


public static boolean getRotationMatrix(float[] R, float[] I, float[] gravity, float[] geomagnetic) 

Source Link

Document

Computes the inclination matrix I as well as the rotation matrix R transforming a vector from the device coordinate system to the world's coordinate system which is defined as a direct orthonormal basis, where:

  • X is defined as the vector product Y.Z (It is tangential to the ground at the device's current location and roughly points East).
  • Y is tangential to the ground at the device's current location and points towards the magnetic North Pole.
  • Z points towards the sky and is perpendicular to the ground.

World coordinate-system diagram.Usage

From source file:radu.pidroid.Controller.java

private void computeTiltAngle() {
    float[] mRotationMatrix = new float[9];
    float[] mOrientationMatrix = new float[3];

    ///*from   w ww .  j ava2  s .c  o m*/
    if (!SensorManager.getRotationMatrix(mRotationMatrix, null, mAccelerometerData, mGeomagneticData))
        return;
    else
        SensorManager.getOrientation(mRotationMatrix, mOrientationMatrix);

    //
    turnAngle = (int) Math.round(Math.toDegrees((double) mOrientationMatrix[1]) + 90);
}

From source file:com.dragon4.owo.ar_trace.ARCore.MixView.java

public void onSensorChanged(SensorEvent evt) {
    try {//  w w w. j  a v  a  2 s .co  m
        //         killOnError();

        // ?? , ?  ???  ? ? ? 
        if (evt.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            grav[0] = evt.values[0];
            grav[1] = evt.values[1];
            grav[2] = evt.values[2];

            augScreen.postInvalidate(); // ? 
        } else if (evt.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
            mag[0] = evt.values[0];
            mag[1] = evt.values[1];
            mag[2] = evt.values[2];

            augScreen.postInvalidate(); // ? 
        }

        //  ? 
        SensorManager.getRotationMatrix(RTmp, I, grav, mag);
        //  (?)
        SensorManager.remapCoordinateSystem(RTmp, SensorManager.AXIS_X, SensorManager.AXIS_MINUS_Z, Rot);

        //  ? ? 
        tempR.set(Rot[0], Rot[1], Rot[2], Rot[3], Rot[4], Rot[5], Rot[6], Rot[7], Rot[8]);

        //       ,  
        finalR.toIdentity();
        finalR.prod(m4);
        finalR.prod(m1);
        finalR.prod(tempR);
        finalR.prod(m3);
        finalR.prod(m2);
        finalR.invert();

        // ? ?  ? ??   ...
        histR[rHistIdx].set(finalR);
        rHistIdx++;
        if (rHistIdx >= histR.length)
            rHistIdx = 0;

        smoothR.set(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f);
        for (int i = 0; i < histR.length; i++) {
            smoothR.add(histR[i]);
        }
        smoothR.mult(1 / (float) histR.length);

        synchronized (mixContext.rotationM) {
            mixContext.rotationM.set(smoothR);
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.spoiledmilk.ibikecph.navigation.SMRouteNavigationMapFragment.java

public void onSensorChanged(SensorEvent event) {

    if (event.sensor == mAccelerometer) {
        accValues.put(event.values);//from  www.j a  v a  2s .  c om
        // System.arraycopy(event.values, 0, mLastAccelerometer, 0, event.values.length);
        mLastAccelerometerSet = true;
    } else if (event.sensor == mMagnetometer) {
        if (Math.sqrt(event.values[0] * event.values[0] + event.values[1] * event.values[1]
                + event.values[2] * event.values[2]) > SensorManager.MAGNETIC_FIELD_EARTH_MAX * 1.5) {
            return;
        }
        if (event.values.length < 3) {
            return;
        }
        magValues.put(event.values);
        // System.arraycopy(event.values, 0, mLastMagnetometer, 0, event.values.length);
        mLastMagnetometerSet = true;
    }

    if (mLastAccelerometerSet && mLastMagnetometerSet) {
        SensorManager.getRotationMatrix(mR, null, accValues.get(), magValues.get());
        // SensorManager.remapCoordinateSystem(mR, SensorManager.AXIS_X,
        // SensorManager.AXIS_Z, remapMatrix);
        SensorManager.getOrientation(mR, mOrientation); // remapMatrx
        if (SMLocationManager.getInstance().hasValidLocation()) {
            Location currentLoc = SMLocationManager.getInstance().getLastValidLocation();
            float azimuth = -(float) Math.toDegrees(mOrientation[0]);
            final GeomagneticField geoField = new GeomagneticField(
                    Double.valueOf(currentLoc.getLatitude()).floatValue(),
                    Double.valueOf(currentLoc.getLongitude()).floatValue(),
                    Double.valueOf(currentLoc.getAltitude()).floatValue(), System.currentTimeMillis());
            azimuth += geoField.getDeclination(); // converts magnetic north
            // into true north
            // LOG.d("azimuth = " + azimuth);
            compassOrientation = azimuth;// - bearing;
            // if (Math.abs(locationOverlay.compassOrientation - compassOrientation) > 5) {
            // locationOverlay.compassOrientation = compassOrientation;
            // mapView.invalidate();
            // }
            // }
            // }
        }
    }
}

From source file:org.mixare.MixViewActivity.java

public void onSensorChanged(SensorEvent evt) {
    try {/*  www . j  a v  a 2s . co  m*/
        if (getMixViewData().getSensorGyro() != null) {

            if (evt.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
                getMixViewData().setGyro(evt.values);
            }

            if (evt.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                getMixViewData().setGrav(
                        getMixViewData().getGravFilter().lowPassFilter(evt.values, getMixViewData().getGrav()));
            } else if (evt.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
                getMixViewData().setMag(
                        getMixViewData().getMagFilter().lowPassFilter(evt.values, getMixViewData().getMag()));
            }
            getMixViewData().setAngle(getMixViewData().getMagFilter().complementaryFilter(
                    getMixViewData().getGrav(), getMixViewData().getGyro(), 30, getMixViewData().getAngle()));

            SensorManager.getRotationMatrix(getMixViewData().getRTmp(), getMixViewData().getI(),
                    getMixViewData().getGrav(), getMixViewData().getMag());
        } else {
            if (evt.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                getMixViewData().setGrav(evt.values);
            } else if (evt.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
                getMixViewData().setMag(evt.values);
            }
            SensorManager.getRotationMatrix(getMixViewData().getRTmp(), getMixViewData().getI(),
                    getMixViewData().getGrav(), getMixViewData().getMag());
        }

        //         augmentedView.postInvalidate();
        hudView.postInvalidate();
        projectedMapView.postInvalidate();

        int rotation = Compatibility.getRotation(this);

        if (rotation == 1) {
            SensorManager.remapCoordinateSystem(getMixViewData().getRTmp(), SensorManager.AXIS_X,
                    SensorManager.AXIS_MINUS_Z, getMixViewData().getRot());
        } else {
            SensorManager.remapCoordinateSystem(getMixViewData().getRTmp(), SensorManager.AXIS_Y,
                    SensorManager.AXIS_MINUS_Z, getMixViewData().getRot());
        }
        getMixViewData().getTempR().set(getMixViewData().getRot()[0], getMixViewData().getRot()[1],
                getMixViewData().getRot()[2], getMixViewData().getRot()[3], getMixViewData().getRot()[4],
                getMixViewData().getRot()[5], getMixViewData().getRot()[6], getMixViewData().getRot()[7],
                getMixViewData().getRot()[8]);

        getMixViewData().getFinalR().toIdentity();
        getMixViewData().getFinalR().prod(getMixViewData().getM4());
        getMixViewData().getFinalR().prod(getMixViewData().getM1());
        getMixViewData().getFinalR().prod(getMixViewData().getTempR());
        getMixViewData().getFinalR().prod(getMixViewData().getM3());
        getMixViewData().getFinalR().prod(getMixViewData().getM2());
        getMixViewData().getFinalR().invert();

        getMixViewData().getHistR()[getMixViewData().getrHistIdx()].set(getMixViewData().getFinalR());

        int histRLenght = getMixViewData().getHistR().length;

        getMixViewData().setrHistIdx(getMixViewData().getrHistIdx() + 1);
        if (getMixViewData().getrHistIdx() >= histRLenght)
            getMixViewData().setrHistIdx(0);

        getMixViewData().getSmoothR().set(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f);
        for (int i = 0; i < histRLenght; i++) {
            getMixViewData().getSmoothR().add(getMixViewData().getHistR()[i]);
        }
        getMixViewData().getSmoothR().mult(1 / (float) histRLenght);

        MixContext.getInstance().updateSmoothRotation(getMixViewData().getSmoothR());

        //         float[] orientation = new float[3];
        //            float[] rTemp = getMixViewData().getRTmp();
        //         SensorManager.getOrientation(rTemp, orientation);
        //            Log.d("PROJECT_MAP", "Sensor Angles");
        //         Log.d("PROJECT_MAP", orientation[0] + ", " + orientation[1] + ", " + orientation[2]);
        //            Log.d("PROJECT_MAP", "Rotation Matrix Before Smoothing");
        //            Log.d("PROJECT_MAP", rTemp[0] + ", " + rTemp[1] + ", " + rTemp[2]);
        //            Log.d("PROJECT_MAP", rTemp[3] + ", " + rTemp[4] + ", " + rTemp[5]);
        //            Log.d("PROJECT_MAP", rTemp[6] + ", " + rTemp[7] + ", " + rTemp[8]);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:ibme.sleepap.recording.SignalsRecorder.java

@Override
public void onSensorChanged(SensorEvent event) {
    synchronized (this) {
        // Checking which type of sensor called this listener
        // In this case it is the Accelerometer (the next is the Magnetomer)
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            accelerometerCurrentTime = System.currentTimeMillis();

            if (accelerometerCurrentTime
                    - lastAccelerometerReadTime > (1000 / Constants.PARAM_SAMPLERATE_ACCELEROMETER
                            - 1000 / (Constants.PARAM_SAMPLERATE_ACCELEROMETER
                                    * Constants.PARAM_UPSAMPLERATE_ACCELEROMETER))) {
                lastAccelerometerReadTime = accelerometerCurrentTime;
                float xRaw = event.values[0];
                float yRaw = event.values[1];
                float zRaw = event.values[2];

                // Extracts unwanted gravity component from the
                // accelerometer signal.
                float alpha = Constants.PARAM_GRAVITY_FILTER_COEFFICIENT;
                runningGravityComponents[0] = runningGravityComponents[0] * alpha + (1 - alpha) * xRaw;
                runningGravityComponents[1] = runningGravityComponents[1] * alpha + (1 - alpha) * yRaw;
                runningGravityComponents[2] = runningGravityComponents[2] * alpha + (1 - alpha) * zRaw;

                float xAccel = xRaw - runningGravityComponents[0];
                float yAccel = yRaw - runningGravityComponents[1];
                float zAccel = zRaw - runningGravityComponents[2];

                double magnitudeSquare = xAccel * xAccel + yAccel * yAccel + zAccel * zAccel;
                double magnitude = Math.sqrt(magnitudeSquare);

                actigraphyQueue.add(magnitude);
                int secsToDisplay = Integer.parseInt(sharedPreferences.getString(Constants.PREF_GRAPH_SECONDS,
                        Constants.DEFAULT_GRAPH_RANGE));
                int numberExtraSamples = actigraphyQueue.size()
                        - (secsToDisplay * Constants.PARAM_SAMPLERATE_ACCELEROMETER);
                if (numberExtraSamples > 0) {
                    for (int i = 0; i < numberExtraSamples; i++) {
                        actigraphyQueue.remove();
                    }//from   w w w  .j  av  a2  s .  com
                }

                // Saves accelerometer data, necessary for the orientation
                // computation
                System.arraycopy(event.values, 0, latestAccelerometerEventValues, 0, 3);
                pushBackAccelerometerValues(xRaw, yRaw, zRaw);

                if (accelerometerCurrentTime
                        - lastAccelerometerRecordedTime > Constants.PARAM_ACCELEROMETER_RECORDING_PERIOD
                                + 1000 / Constants.PARAM_SAMPLERATE_ACCELEROMETER) {
                    if (startRecordingFlag) {
                        writeActigraphyLogVariance();
                    }
                    gravitySum = gravitySquaredSum = 0;
                    varianceCounter = 0;
                    lastAccelerometerRecordedTime = accelerometerCurrentTime;
                }
                if (startRecordingFlag) {
                    writeRawActigraphy();
                }
            }
        }

        // Checking if the Magnetomer called this listener
        if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {

            // Copying magnetometer measures.
            System.arraycopy(event.values, 0, mGeoMags, 0, 3);

            if (SensorManager.getRotationMatrix(mRotationM, null, latestAccelerometerEventValues, mGeoMags)) {
                SensorManager.getOrientation(mRotationM, mOrientation);

                // Finding current orientation requires both Accelerometer
                // (using the previous measure) and Magnetometer data.
                // Converting radians to degrees (yaw, pitch, roll)
                mOrientation[0] = mOrientation[0] * Constants.CONST_DEGREES_PER_RADIAN;
                mOrientation[1] = mOrientation[1] * Constants.CONST_DEGREES_PER_RADIAN;
                mOrientation[2] = mOrientation[2] * Constants.CONST_DEGREES_PER_RADIAN;

                // The values (1,2,3,4) attributed for
                // supine/prone/left/right match the
                // ones attributed in VISI text files.
                int positionValue = 0;
                // Supine (4).
                if (-45 < mOrientation[1] && mOrientation[1] < 45 && -45 < mOrientation[2]
                        && mOrientation[2] < 45) {
                    positionValue = Constants.CODE_POSITION_SUPINE;
                    position = Position.Supine;
                }

                // Prone (1).
                if ((((-180 < mOrientation[2] && mOrientation[2] < -135)
                        || (135 < mOrientation[2] && mOrientation[2] < 180)) && -45 < mOrientation[1]
                        && mOrientation[1] < 45)) {
                    positionValue = Constants.CODE_POSITION_PRONE;
                    position = Position.Prone;
                }

                // Right (2).
                if (-90 < mOrientation[2] && mOrientation[2] < -45) {
                    positionValue = Constants.CODE_POSITION_RIGHT;
                    position = Position.Right;
                }

                // Left (3).
                if (45 < mOrientation[2] && mOrientation[2] < 90) {
                    positionValue = Constants.CODE_POSITION_LEFT;
                    position = Position.Left;
                }

                // Sitting up (5).
                if ((((-135 < mOrientation[1] && mOrientation[1] < -45)
                        || (45 < mOrientation[1] && mOrientation[1] < 135)) && -45 < mOrientation[2]
                        && mOrientation[2] < 45)) {
                    positionValue = Constants.CODE_POSITION_SITTING;
                    position = Position.Sitting;
                }

                if ((oldPositionValue != positionValue) && (positionValue != 0) && startRecordingFlag) {
                    updatePositionChangeTime(oldPositionValue);
                    oldPositionValue = positionValue;
                    try {
                        // Write raw body position data
                        BufferedWriter orientationBufferedWriter = new BufferedWriter(
                                new FileWriter(orientationFile, true));
                        orientationBufferedWriter.append(String.valueOf(System.currentTimeMillis()) + ",");
                        orientationBufferedWriter.append(String.valueOf(positionValue) + "\n");
                        orientationBufferedWriter.flush();
                        orientationBufferedWriter.close();
                    } catch (IOException e) {
                        Log.e(Constants.CODE_APP_TAG, "Error writing orientation data to file", e);
                    }
                }
            }
        }
    }
}

From source file:com.davidmascharka.lips.TrackerActivity.java

@Override
public void onSensorChanged(SensorEvent event) {
    switch (event.sensor.getType()) {
    case Sensor.TYPE_ACCELEROMETER:
        accelerometerX = event.values[0];
        accelerometerY = event.values[1];
        accelerometerZ = event.values[2];
        break;//from   w w  w  .  j  ava 2  s  . c  om
    case Sensor.TYPE_MAGNETIC_FIELD:
        magneticX = event.values[0];
        magneticY = event.values[1];
        magneticZ = event.values[2];
        break;
    case Sensor.TYPE_LIGHT:
        light = event.values[0];
        break;
    case Sensor.TYPE_ROTATION_VECTOR:
        rotationX = event.values[0];
        rotationY = event.values[1];
        rotationZ = event.values[2];
        break;
    default:
        break;
    }

    SensorManager.getRotationMatrix(rotation, inclination,
            new float[] { accelerometerX, accelerometerY, accelerometerZ },
            new float[] { magneticX, magneticY, magneticZ });
    orientation = SensorManager.getOrientation(rotation, orientation);
}

From source file:com.example.sensingapp.SensingApp.java

private boolean calculateOrientation() {
    float[] arrfValues = new float[3];
    float[] arrfR = new float[9];
    float[] arrfI = new float[9];

    if ((m_arrfAcclValues == null) || (m_arrfMagnetValues == null)) {
        return false;
    }//from   ww w  . ja va2  s .  co  m

    //if (SensorManager.getRotationMatrix(arrfR, null, m_arrfAcclValues, m_arrfMagnetValues)) {    //Ignore inclintion matrix calculation will make the execution faster

    if (SensorManager.getRotationMatrix(arrfR, arrfI, m_arrfAcclValues, m_arrfMagnetValues)) {
        SensorManager.getOrientation(arrfR, arrfValues);
        m_arrfOrientValues[0] = (float) Math.toDegrees(arrfValues[0]);
        m_arrfOrientValues[1] = (float) Math.toDegrees(arrfValues[1]);
        m_arrfOrientValues[2] = (float) Math.toDegrees(arrfValues[2]);

        if (m_arrfOrientValues[0] < 0) {
            m_arrfOrientValues[0] = m_arrfOrientValues[0] + 360; // Make Azimuth 0 ~ 360
        }

        return true;
    } else {
        return false;
    }

}