@Override
  public void onSensorChanged(SensorEvent event) {

    switch (event.sensor.getType()) {
      case Sensor.TYPE_ACCELEROMETER:
        for (int i = 0; i < 3; i++) {
          System.out.println("event value:" + event.values[i]);
          valuesAccelerometer[i] = event.values[i];
        }
        break;
      case Sensor.TYPE_MAGNETIC_FIELD:
        for (int i = 0; i < 3; i++) {
          System.out.println("event value2:" + event.values[i]);
          valuesMagneticField[i] = event.values[i];
        }
        break;
    }

    boolean success =
        SensorManager.getRotationMatrix(matrixR, matrixI, valuesAccelerometer, valuesMagneticField);

    if (success) {
      SensorManager.getOrientation(matrixR, matrixValues);

      double azimuth = Math.toDegrees(matrixValues[0]);
      double pitch = Math.toDegrees(matrixValues[1]);
      double roll = Math.toDegrees(matrixValues[2]);

      System.out.println("orientation[0]: azimut: " + azimuth);
      System.out.println("orientation[1]: pitch : " + pitch);
      System.out.println("orientation[2]: roll: " + roll);
    }
  }
예제 #2
0
  @Override
  public void onSensorChanged(SensorEvent event) {

    DecimalFormat oneDigit = new DecimalFormat("#,##0.0");

    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {

      rawAccel = event.values.clone();
      accel[0] = event.values[0];
      accel[1] = event.values[1];
      accel[2] = event.values[2];

      String xPrepend, yPrepend, zPrepend, data = "";

      xPrepend = accel[0] > 0 ? "+" : "";
      yPrepend = accel[1] > 0 ? "+" : "";
      zPrepend = accel[2] > 0 ? "+" : "";

      if (x) {
        data = "X: " + xPrepend + oneDigit.format(accel[0]);
      }
      if (y) {
        if (!data.equals("")) {
          data += " , Y: " + yPrepend + oneDigit.format(accel[1]);
        } else {
          data += "Y: " + yPrepend + oneDigit.format(accel[1]);
        }
      }
      if (z) {
        if (!data.equals("")) {
          data += " , Z: " + zPrepend + oneDigit.format(accel[2]);
        } else {
          data += "Z: " + zPrepend + oneDigit.format(accel[2]);
        }
      }

      if (mag) {
        accel[3] =
            (float)
                Math.sqrt(Math.pow(accel[0], 2) + Math.pow(accel[1], 2) + Math.pow(accel[2], 2));

        if (!data.equals("")) {
          data += " , Magnitude: " + oneDigit.format(accel[3]);
        } else {
          data += "Magnitude: " + oneDigit.format(accel[3]);
        }
      }
      values.setText(data);

    } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
      rawMag = event.values.clone();

      float rotation[] = new float[9];

      if (SensorManager.getRotationMatrix(rotation, null, rawAccel, rawMag)) {
        orientation = new float[3];
        SensorManager.getOrientation(rotation, orientation);
      }
    }
  }
예제 #3
0
 /** calculates orientation angles from accelerometer and magnetometer output */
 private void calculateAccMagOrientation() {
   if (SensorManager.getRotationMatrix(rotationMatrix, null, accel, magnet)) {
     float[] tempMatrix = new float[9];
     if (portrait) {
       // dont remap in portrait
       if (isTablet) {
         SensorManager.remapCoordinateSystem(
             rotationMatrix, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, tempMatrix);
       } else {
         SensorManager.remapCoordinateSystem(
             rotationMatrix, SensorManager.AXIS_X, SensorManager.AXIS_Y, tempMatrix);
       }
     } else {
       // remap in landscape
       if (isTablet) {
         SensorManager.remapCoordinateSystem(
             rotationMatrix, SensorManager.AXIS_X, SensorManager.AXIS_Y, tempMatrix);
       } else {
         SensorManager.remapCoordinateSystem(
             rotationMatrix, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, tempMatrix);
       }
     }
     SensorManager.getOrientation(tempMatrix, accMagOrientation);
     rotationMatrix = tempMatrix;
   }
 }
예제 #4
0
  public void onSensorChanged(SensorEvent event) {

    boolean gotRotation =
        SensorManager.getRotationMatrix(rotation, identity, lastAccelerometer, lastCompass);
    switch (event.sensor.getType()) {
      case Sensor.TYPE_ROTATION_VECTOR:
        break;
      case Sensor.TYPE_MAGNETIC_FIELD:
        lastCompass = exponentialSmoothing(event.values, lastCompass, ALPHA);
        break;
      case Sensor.TYPE_ACCELEROMETER:
        lastAccelerometer = exponentialSmoothing(event.values, lastAccelerometer, ALPHA);

        break;
    }
    if (gotRotation) {
      float cameraRotation[] = new float[9];
      // remap such that the camera is pointing straight down the Y axis
      SensorManager.remapCoordinateSystem(
          rotation, SensorManager.AXIS_X, SensorManager.AXIS_Z, cameraRotation);

      // orientation vector
      orientation = new float[3];
      SensorManager.getOrientation(cameraRotation, orientation);
    }
  }
예제 #5
0
 private void calculateOrientation() {
   initialRotationMatrix = new float[9];
   if (accellerometerValues != null && magneticFieldValues != null) {
     hasInitialOrientation =
         SensorManager.getRotationMatrix(
             initialRotationMatrix, null, accellerometerValues, magneticFieldValues);
   }
 }
예제 #6
0
 private void updateOrientation() {
   if (SensorManager.getRotationMatrix(R, null, accelerometerValues, magneticFieldValues)) {
     SensorManager.getOrientation(R, orientation);
     azimuth = (float) Math.toDegrees(orientation[0]);
     pitch = (float) Math.toDegrees(orientation[1]);
     roll = (float) Math.toDegrees(orientation[2]);
   }
 }
예제 #7
0
  @Override
  public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
      magnetic_field_values[0] =
          (float) (magnetic_field_values[0] * (1.0 - KFILTER) + event.values[0] * KFILTER);
      magnetic_field_values[1] =
          (float) (magnetic_field_values[1] * (1.0 - KFILTER) + event.values[1] * KFILTER);
      magnetic_field_values[2] =
          (float) (magnetic_field_values[2] * (1.0 - KFILTER) + event.values[2] * KFILTER);
    }
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
      accelerometer_values[0] =
          (float) (accelerometer_values[0] * (1.0 - KFILTER) + event.values[0] * KFILTER);
      accelerometer_values[1] =
          (float) (accelerometer_values[1] * (1.0 - KFILTER) + event.values[1] * KFILTER);
      accelerometer_values[2] =
          (float) (accelerometer_values[2] * (1.0 - KFILTER) + event.values[2] * KFILTER);

      rollingZ = (float) ((accelerometer_values[2] * KFILTER) + rollingZ * (1.0 - KFILTER));
      rollingX = (float) ((accelerometer_values[0] * KFILTER) + rollingX * (1.0 - KFILTER));

      if (rollingZ != 0.0f) {
        inclination = (float) Math.atan(rollingX / rollingZ);
      } else if (rollingX < 0) {
        inclination = (float) (Math.PI / 2.0);
      } else if (rollingX >= 0) {
        inclination = (float) (3 * Math.PI / 2.0);
      }

      inclination = (float) (inclination * (360 / (2 * Math.PI)));
      if (inclination < 0) inclination += 90;
      else inclination -= 90;
    }

    if (magnetic_field_values != null && accelerometer_values != null) {

      float[] R = new float[MATRIX_SIZE];
      float[] I = new float[MATRIX_SIZE];

      if (SensorManager.getRotationMatrix(R, I, accelerometer_values, magnetic_field_values)) {

        float[] orientation_values = new float[3];
        SensorManager.remapCoordinateSystem(R, SensorManager.AXIS_X, SensorManager.AXIS_Z, R);
        SensorManager.getOrientation(R, orientation_values);

        // radians
        float azimuth = (float) Math.toDegrees(orientation_values[0]);
        azimuth = (azimuth + 360) % 360;

        direction = (float) ((azimuth * KFILTER) + direction * (1.0 - KFILTER));
      }
    }

    scoreView.setText("Score: " + score);
    timeView.setText(String.format("Time Remaining: %.2f", timeRemaining));
  }
예제 #8
0
  @Override
  public void onSensorChanged(SensorEvent event) {
    /**
     * This method bring the user to the next screen.
     *
     * <p>show the usage of various javadoc Tags.
     *
     * @param view
     * @return Nothing
     */
    // Log.d(TAG, "onSensorChanged()");
    if (event.values == null) {
      Log.w(TAG, "event.values is null");
      return;
    }
    int sensorType = event.sensor.getType();
    switch (sensorType) {
      case Sensor.TYPE_ACCELEROMETER:
        mGravity = event.values;
        break;
      case Sensor.TYPE_MAGNETIC_FIELD:
        mGeomagnetic = event.values;
        break;
      default:
        Log.w(TAG, "Unknown sensor type " + sensorType);
        return;
    }
    if (mGravity == null) {
      Log.w(TAG, "mGravity is null");
      return;
    }
    if (mGeomagnetic == null) {
      Log.w(TAG, "mGeomagnetic is null");
      return;
    }
    float R[] = new float[9];
    if (!SensorManager.getRotationMatrix(R, null, mGravity, mGeomagnetic)) {
      Log.w(TAG, "getRotationMatrix() failed");
      return;
    }

    float orientation[] = new float[9];
    SensorManager.getOrientation(R, orientation);
    // Orientation contains: azimuth, pitch and roll - we'll use roll
    float azimuth = orientation[0];
    int azimuthDeg = (int) Math.round(Math.toDegrees(azimuth));
    int azimuthPower = degreesToPower(azimuthDeg);
    // Log.d(TAG, "deg=" + rollDeg + " power=" + power);
    tv.setText(String.valueOf(azimuthPower));
  }
예제 #9
0
        @Override
        public void onSensorChanged(SensorEvent sensorEvent) {
          float[] values = sensorEvent.values;

          int sensorType = sensorEvent.sensor.getType();
          if (sensorType == Sensor.TYPE_ACCELEROMETER) {
            for (int i = 0; i < 3; i++) {
              valuesAccelerometerValues[i] += values[i];
            }

            ++samplesAccelerometer;
          } else if (sensorType == Sensor.TYPE_MAGNETIC_FIELD) {
            for (int i = 0; i < 3; i++) {
              valuesMagneticFieldValues[i] += values[i];
            }

            ++samplesMagneticSensor;
          }

          if (samplesAccelerometer > requiredAccelerometerSamples
              && samplesMagneticSensor > requiredMagneticSensorSamples) {

            for (int i = 0; i < 3; i++) {
              valuesAccelerometerValues[i] =
                  valuesAccelerometerValues[i] / (float) samplesAccelerometer;
              valuesMagneticFieldValues[i] =
                  valuesMagneticFieldValues[i] / (float) samplesMagneticSensor;
            }

            boolean success =
                SensorManager.getRotationMatrix(
                    matrixR,
                    null /*matrixI*/,
                    valuesAccelerometerValues,
                    valuesMagneticFieldValues);

            if (success) {
              SensorManager.getOrientation(matrixR, matrixValues);
              ArenaActivity.this.sendDeviceOrientationData(matrixValues);
            }

            valuesAccelerometerValues[0] =
                valuesAccelerometerValues[1] = valuesAccelerometerValues[2] = 0.0f;
            valuesMagneticFieldValues[0] =
                valuesMagneticFieldValues[1] = valuesMagneticFieldValues[2] = 0.0f;
            samplesAccelerometer = samplesMagneticSensor = 0;
          }
        }
예제 #10
0
  public void onSensorChanged(SensorEvent se) {
    if (se.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {

      SensorManager.getRotationMatrix(R, I, gravityLocal, se.values); // Sets up the R array		
      orientationArray = SensorManager.getOrientation(R, orientationArray);
      orientation.setText(
          "Orientation: "
              + String.format(
                  "(%.3f, %.3f, %.3f)",
                  orientationArray[0], orientationArray[1], orientationArray[2]));
      output.setText(
          "Magnetic Field: "
              + String.format("(%.3f, %.3f, %.3f)", se.values[0], se.values[1], se.values[2]));
      graphpoint.addPoint(orientationArray);
    }
  }
예제 #11
0
 @Override
 public void onSensorChanged(SensorEvent event) {
   Sensor sensor = event.sensor;
   if (sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
     if (first) {
       first = false;
       System.out.println("error first");
       // Toast.makeText(this, "sensor result", Toast.LENGTH_LONG).show();
       count1 = Float.parseFloat(String.valueOf(event.values[0]));
     }
     if (activityRunning) {
       System.out.println("error later");
       // Toast.makeText(this, "sensor value 1", Toast.LENGTH_LONG).show();
       drawView.invalidate();
       count.setText((Float.parseFloat(String.valueOf(event.values[0])) - count1) + "");
     }
   }
   if (event.sensor == mAccelerometer) {
     System.arraycopy(event.values, 0, mLastAccelerometer, 0, event.values.length);
     mLastAccelerometerSet = true;
   } else if (event.sensor == mMagnetometer) {
     System.arraycopy(event.values, 0, mLastMagnetometer, 0, event.values.length);
     mLastMagnetometerSet = true;
   }
   if (mLastAccelerometerSet && mLastMagnetometerSet) {
     Toast.makeText(this, "I am here", Toast.LENGTH_LONG).show();
     SensorManager.getRotationMatrix(mR, null, mLastAccelerometer, mLastMagnetometer);
     SensorManager.getOrientation(mR, mOrientation);
     float azimuthInRadians = mOrientation[0];
     float azimuthInDegress = (float) (Math.toDegrees(azimuthInRadians) + 360) % 360;
     angle.setText(azimuthInRadians + " radians and " + azimuthInDegress + " degrees");
     float diff = Math.abs(azimuthInDegress - previousdegree);
     if (diff > 90) {
       previousdegree = azimuthInDegress;
       if (azimuthInDegress < 45 || azimuthInDegress > 315) {
         drawView.current = DrawView.Side.North;
       } else if (azimuthInDegress > 45 || azimuthInDegress < 135) {
         drawView.current = DrawView.Side.East;
       } else if (azimuthInDegress > 135 || azimuthInDegress < 225) {
         drawView.current = DrawView.Side.South;
       } else {
         drawView.current = DrawView.Side.West;
       }
     }
   }
 }
예제 #12
0
  @Override
  public void onSensorChanged(SensorEvent event) {
    // if (!computing.compareAndSet(false, true)) return;
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
      /*smoothed = LowPassFilter.filter(event.values, grav);
      grav[0] = smoothed[0];
      grav[1] = smoothed[1];
      grav[2] = smoothed[2];*/
      grav[0] = event.values[0];
      grav[1] = event.values[1];
      grav[2] = event.values[2];
    } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
      /*            smoothed = LowPassFilter.filter(event.values, mag);
                  mag[0] = smoothed[0];
                  mag[1] = smoothed[1];
                  mag[2] = smoothed[2];
      */
      mag[0] = event.values[0];
      mag[1] = event.values[1];
      mag[2] = event.values[2];
    }

    // Get rotation matrix given the gravity and geomagnetic matrices
    SensorManager.getRotationMatrix(rotation, null, grav, mag);
    SensorManager.getOrientation(rotation, orientation);
    floatBearing = orientation[0];

    // Convert from radians to degrees
    floatBearing = Math.toDegrees(floatBearing); // degrees east of true north (180 to -180)

    // Compensate for the difference between true north and magnetic north
    if (gmf != null) floatBearing += gmf.getDeclination();

    // adjust to 0-360
    if (floatBearing < 0) floatBearing += 360;

    computing.set(false);

    builder.setLength(0);
    builder.append("X " + rotation[0] + "\nY " + rotation[1] + "\nZ " + rotation[2] + "\n");
    builder.append("X " + rotation[3] + "\nY " + rotation[4] + "\nZ " + rotation[5] + "\n");
    builder.append("X " + rotation[6] + "\nY " + rotation[7] + "\nZ " + rotation[8] + "\n");
    textView.setText(builder.toString());
  }
  /** Calculates orientation angles from accelerometer and magnetometer output. */
  private void calculateOrientation() {
    // To get the orientation vector from the acceleration and magnetic
    // sensors, we let Android do the heavy lifting. This call will
    // automatically compensate for the tilt of the compass and fail if the
    // magnitude of the acceleration is not close to 9.82m/sec^2. You could
    // perform these steps yourself, but in my opinion, this is the best way
    // to do it.
    if (SensorManager.getRotationMatrix(rotationMatrix, null, acceleration, magnetic)) {
      SensorManager.getOrientation(rotationMatrix, baseOrientation);

      getRotationVectorFromAccelMag(baseOrientation);

      if (!hasOrientation) {
        quatGyro = new Quaternion(quatAccelMag.getScalarPart(), quatAccelMag.getVectorPart());
      }

      hasOrientation = true;
    }
  }
예제 #14
0
  public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) mGravity = event.values;
    if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) mGeomagnetic = event.values;
    if (mGravity != null && mGeomagnetic != null) {
      float R[] = new float[9];
      float I[] = new float[9];
      boolean success = SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic);
      if (success) {
        float orientation[] = new float[3];
        SensorManager.getOrientation(R, orientation);
        azimut = orientation[0]; // orientation contains: azimut,
        // pitch
        // and roll
      }
    }

    msg = new Message();
    msg.obj = azimut;
    if (handler != null) handler.sendMessage(msg);
  }
 public void onSensorChanged(SensorEvent event) {
   if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
     if (magnetic != null) {
       SensorManager.getRotationMatrix(baseR, null, event.values, magnetic);
     }
     if (baseR != null) SensorManager.getOrientation(baseR, currR);
   } else {
     if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
       magnetic = event.values;
     }
   }
   int orientation = display.getOrientation();
   if (currR != null)
     switch (orientation) {
       case (1):
         mLayout.setDepth((int) (MAX_DEPTH * (1.7f + currR[2])));
         break;
       default:
         mLayout.setDepth((int) (MAX_DEPTH * (currR[1] + 1.4f)));
         break;
     }
 }
예제 #16
0
        public void onSensorChanged(final SensorEvent event) {
          if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE) return;

          switch (event.sensor.getType()) {
            case Sensor.TYPE_ACCELEROMETER:
              System.arraycopy(
                  event.values, 0, gravity, 0, Math.min(event.values.length, gravity.length));
              break;
            case Sensor.TYPE_MAGNETIC_FIELD:
              System.arraycopy(
                  event.values, 0, geomag, 0, Math.min(event.values.length, geomag.length));
              break;
          }

          if (gravity != null && geomag != null && bearingsListener != null) {
            if (SensorManager.getRotationMatrix(inR, I, gravity, geomag)) {
              SensorManager.getOrientation(inR, orientVals);
              final int bearing = (int) Utils.GeoUtils.radToBearing(orientVals[0]);

              bearingsListener.onPhoneBearingChanged(bearing);
            }
          }
        }
예제 #17
0
 @Override
 public void onSensorChanged(SensorEvent event) {
   switch (event.sensor
       .getType()) { //  both accelerometer and magnetic data are needed to compute orientation
     case Sensor.TYPE_ACCELEROMETER:
       System.arraycopy(event.values, 0, accelValues, 0, 3);
       if (compassValues[0] != 0) sensorsReady = true;
       break;
     case Sensor.TYPE_MAGNETIC_FIELD:
       System.arraycopy(event.values, 0, compassValues, 0, 3);
       if (accelValues[2] != 0) sensorsReady = true;
       break;
     default:
       break;
   }
   if (sensorsReady
       && SensorManager.getRotationMatrix(inR, inclineMatrix, accelValues, compassValues)) {
     SensorManager.getOrientation(inR, prefValues);
     pitch = (float) Math.toDegrees(prefValues[1]);
     roll = (float) Math.toDegrees(prefValues[2]);
     if (mc != null) mc.updateOrientation(pitch, roll); // Update character's position
   }
 }
    @Override
    public void onSensorChanged(SensorEvent event) {
      if (paused) {
        return;
      }

      long currentTime = SystemClock.elapsedRealtime();
      if (currentTime < mCompassUpdateNextTimestamp) {
        return;
      }

      if (event.sensor == mAccelerometer) {
        System.arraycopy(event.values, 0, mLastAccelerometer, 0, event.values.length);
        mLastAccelerometerSet = true;
      } else if (event.sensor == mMagnetometer) {
        System.arraycopy(event.values, 0, mLastMagnetometer, 0, event.values.length);
        mLastMagnetometerSet = true;
      }

      if (mLastAccelerometerSet && mLastMagnetometerSet) {
        SensorManager.getRotationMatrix(mR, null, mLastAccelerometer, mLastMagnetometer);
        SensorManager.getOrientation(mR, mOrientation);
        float azimuthInRadians = mOrientation[0];

        float compassBearing = (float) (Math.toDegrees(azimuthInRadians) + 360) % 360;
        if (compassBearing < 0) {
          // only allow positive degrees
          compassBearing += 360;
        }

        if (compassBearing > mCurrentDegree + 15 || compassBearing < mCurrentDegree - 15) {
          mCurrentDegree = compassBearing;
          setCompass(mCurrentDegree);
        }
      }
      mCompassUpdateNextTimestamp = currentTime + UPDATE_RATE_MS;
    }
  @Override
  public void onSensorChanged(SensorEvent event) {

    if (event.sensor == gyroSensor) {

      synchronized (gyroMonitor) {
        rotX = event.values[0];
        rotY = event.values[1];
        rotZ = event.values[2];
      }
    } else if (event.sensor == magSensor) {
      geomagnetic = event.values;
    } else if (event.sensor == accSensor) {
      gravity = event.values;

      if (geomagnetic != null && gravity != null) {
        boolean success = SensorManager.getRotationMatrix(R, I, gravity, geomagnetic);

        if (success) {
          SensorManager.getOrientation(R, values);

          synchronized (oriMonitor) {
            azimuth = values[0];
            pitch = values[1];
            roll = values[2];
          }
        }
      }
    } else if (event.sensor == linearAccSensor) {
      synchronized (accMonitor) {
        accX = event.values[0];
        accY = event.values[1];
        accZ = event.values[2];
      }
    }
  }
예제 #20
0
파일: b.java 프로젝트: QuantumWorks/APP
    private void a()
    {
        SensorManager.getRotationMatrix(f, null, d, e);
        c;
        JVM INSTR tableswitch 0 1: default 44
    //                   0 44
    //                   1 70;
           goto _L1 _L1 _L2
_L2:
        SensorManager.remapCoordinateSystem(f, 2, 129, f);
_L1:
        float af[] = a;
        SensorManager.getOrientation(f, af);
        int i = -1 + af.length;
        do
        {
            if (i < 0)
            {
                return;
            }
            af[i] = 57.29578F * af[i];
            i--;
        } while (true);
        if (true) goto _L1; else goto _L3
  private float[] calculateOrientation() {
    float[] values = new float[3];
    float[] inR = new float[9];
    float[] outR = new float[9];

    SensorManager.getRotationMatrix(inR, null, mAccelerometerValues, mMagneticValues);

    int xAxis = SensorManager.AXIS_X;
    int yAxis = SensorManager.AXIS_Y;

    switch (mRotation) {
      case Surface.ROTATION_90:
        xAxis = SensorManager.AXIS_Y;
        yAxis = SensorManager.AXIS_MINUS_X;
        break;
      case Surface.ROTATION_180:
        yAxis = SensorManager.AXIS_MINUS_Y;
        break;
      case Surface.ROTATION_270:
        xAxis = SensorManager.AXIS_MINUS_Y;
        yAxis = SensorManager.AXIS_X;
        break;
      default:
        break;
    }

    SensorManager.remapCoordinateSystem(inR, xAxis, yAxis, outR);

    SensorManager.getOrientation(inR, values);

    values[0] = (float) Math.toDegrees(values[0]);
    values[1] = (float) Math.toDegrees(values[1]);
    values[2] = (float) Math.toDegrees(values[2]);

    return values;
  }
예제 #22
0
 /**
  * Returns the rotation matrix describing the devices rotation as per <a href=
  * "http://developer.android.com/reference/android/hardware/SensorManager.html#getRotationMatrix(float[],
  * float[], float[], float[])" >SensorManager#getRotationMatrix(float[], float[], float[],
  * float[])</a>. Does not manipulate the matrix if the platform does not have an accelerometer.
  *
  * @param matrix
  */
 public void getRotationMatrix(float[] matrix) {
   SensorManager.getRotationMatrix(matrix, null, accelerometerValues, magneticFieldValues);
 }
예제 #23
0
  /**
   * @see
   *     http://www.netmite.com/android/mydroid/cupcake/development/samples/Compass/src/com/example/android/compass/CompassActivity.java
   * @see
   *     http://stackoverflow.com/questions/6676377/azimuth-found-with-sensor-type-magnetic-field-much-more-unstable-than-sensor-typ
   * @see http
   *     ://books.google.fr/books?id=c59gCUniP5gC&pg=PA639&lpg=PA639&dq=TYPE_MAGNETIC_FIELD+mapView&source=bl&ots=4wT7sgdYpa&sig=zgNnk9jrZpVfPZRVHtm5kobgiTQ
   *     &hl=fr&sa=X&ei=oy53T9LLD4HB8QOLxMm6DQ&ved=0CD4Q6AEwAg#v=onepage&q=TYPE_MAGNETIC_FIELD%20mapView&f=false
   */
  @Override
  public void onSensorChanged(SensorEvent event) {
    int type = event.sensor.getType();
    // if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE) {
    // if (Log.isLoggable(TAG, Log.DEBUG)) Log.d(TAG, "Could not read SENSOR_STATUS_UNRELIABLE for
    // sennsor " + type);
    // return;
    // }
    float[] data = event.values;
    if (type == Sensor.TYPE_ACCELEROMETER) {
      // alpha is calculated as t / (t + dT)
      // with t, the low-pass filter's time-constant
      // and dT, the event delivery rate
      // final float alpha = 0.9f;
      // gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];
      // gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];
      // gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];

      acceleration[0] = data[0] - gravity[0];
      acceleration[1] = data[1] - gravity[1];
      acceleration[2] = data[2] - gravity[2];
    } else if (type == Sensor.TYPE_MAGNETIC_FIELD) {
      this.sensorMagneticData = data;
    } else if (type == Sensor.TYPE_ORIENTATION) {
      int oldAzimut = this.azimuth;
      this.azimuth = Math.round(event.values[0]);
      if (oldAzimut != this.azimuth) {
        // TODO
        mapView.invalidate();
      }
      return;
    } else {
      // we should not be here.
      return;
    }
    if (true) {

      float[] matrixRotation = new float[16];
      float[] matrixInclination = new float[16];
      SensorManager.getRotationMatrix(
          matrixRotation, matrixInclination, acceleration, sensorMagneticData);
      // float[] outR = new float[16];
      // SensorManager.remapCoordinateSystem(matrixRotation, SensorManager.AXIS_X,
      // SensorManager.AXIS_Z, outR);
      float[] mOrientation = new float[3];
      SensorManager.getOrientation(matrixRotation, mOrientation);
      // Convert the azimuth to degrees in 0.5 degree resolution.
      int newAzimuth = Math.round(Math.round(Math.toDegrees(mOrientation[0])));
      // Adjust the range: 0 < range <= 360 (from: -180 < range <= 180).
      // newAzimuth = (newAzimuth + 360) % 360;
      // alternative newAzimuth = newAzimuth >= 0 ? newAzimuth : newAzimuth + 360;
      //
      if (azimuth != newAzimuth) {
        azimuth = newAzimuth;
        mapView.invalidate();
      }

      // float incl = SensorManager.getInclination(matrixInclination);

    }
  }
예제 #24
0
  public void onSensorChanged(SensorEvent event) {

    KrollDict data = new KrollDict();
    data.put("sType", event.sensor.getType());
    switch (event.sensor.getType()) {
      case Sensor.TYPE_ACCELEROMETER:
        if (event.timestamp - lastSensorAccelerometerEventTimestamp > 100) {
          accellerometerValues = event.values.clone();
          accellerometerValues =
              accelerationFilter.filterFloat(
                  accellerometerValues); // Use a mean filter to smooth the sensor inputs
          accelerationSampleCount++; // Count the number of samples received.

          // Only determine the initial orientation after the acceleration sensor
          // and magnetic sensor have had enough time to be smoothed by the mean
          // filters. Also, only do this if the orientation hasn't already been
          // determined since we only need it once.
          if (accelerationSampleCount > 30 && magneticSampleCount > 30 && !hasInitialOrientation) {
            calculateOrientation();
          }
          // End gyroscope stuffs

          lastSensorAccelerometerEventTimestamp = event.timestamp;

          float[] linear_acceleration = new float[3];
          final float alpha = (float) 0.8;

          gravity[0] = alpha * gravity[0] + (1 - alpha) * accellerometerValues[0];
          gravity[1] = alpha * gravity[1] + (1 - alpha) * accellerometerValues[1];
          gravity[2] = alpha * gravity[2] + (1 - alpha) * accellerometerValues[2];

          linear_acceleration[0] = accellerometerValues[0] - gravity[0];
          linear_acceleration[1] = accellerometerValues[1] - gravity[1];
          linear_acceleration[2] = accellerometerValues[2] - gravity[2];

          float x = accellerometerValues[0];
          float y = accellerometerValues[1];
          float z = accellerometerValues[2];

          data.put("x", x);
          data.put("y", y);
          data.put("z", z);
          data.put("linearAccelerationX", linear_acceleration[0]);
          data.put("linearAccelerationY", linear_acceleration[1]);
          data.put("linearAccelerationZ", linear_acceleration[2]);
        }
        break;
      case Sensor.TYPE_MAGNETIC_FIELD:
        magneticFieldValues = event.values.clone();
        // Gyroscope stuffs.
        magneticFieldValues =
            magneticFilter.filterFloat(
                magneticFieldValues); // Use a mean filter to smooth the sensor inputs
        magneticSampleCount++; // Count the number of samples received.
        // End gyroscope stuffs

        double magnetometer =
            Math.sqrt(
                Math.pow(magneticFieldValues[0], 2)
                    + Math.pow(magneticFieldValues[1], 2)
                    + Math.pow(magneticFieldValues[2], 2));
        data.put("magnetometer", magnetometer);
        data.put("x", magneticFieldValues[0]);
        data.put("y", magneticFieldValues[1]);
        data.put("z", magneticFieldValues[2]);

        if (accellerometerValues != null && magneticFieldValues != null) {

          boolean success =
              SensorManager.getRotationMatrix(R, I, accellerometerValues, magneticFieldValues);
          SensorManager.remapCoordinateSystem(R, SensorManager.AXIS_X, SensorManager.AXIS_Z, outR);
          if (success) {
            SensorManager.getOrientation(R, orientation);
            float azimuthInDegress = (float) (Math.toDegrees(orientation[0]) + 360) % 360;
            data.put("compassRotation", azimuthInDegress);
          }
          SensorManager.getOrientation(outR, orientationPitchRollAzimuth);
          data.put("azimuth", orientationPitchRollAzimuth[0]);
          data.put("pitch", orientationPitchRollAzimuth[1]);
          data.put("roll", orientationPitchRollAzimuth[2]);
        }
        break;
      case Sensor.TYPE_AMBIENT_TEMPERATURE:
        ambiantTemperatureValues = event.values.clone();
        data.put("celcius", ambiantTemperatureValues[0]);
        data.put("fahrenheit", ((ambiantTemperatureValues[0] * 9) / 5) + 32);
        break;
      case Sensor.TYPE_GAME_ROTATION_VECTOR:
        // Approfondire la sortie des infos avec cet example
        // https://github.com/kplatfoot/android-rotation-sensor-sample/blob/master/src/com/kviation/android/sample/orientation/Orientation.java
        /*
        http://developer.android.com/reference/android/hardware/SensorEvent.html#values
        values[0]: x*sin(θ/2)
        values[1]: y*sin(θ/2)
        values[2]: z*sin(θ/2)
        values[3]: cos(θ/2)
        values[4]: estimated heading Accuracy (in radians) (-1 if unavailable)
        */
        gameRotationVectorValues = event.values.clone();
        data.put("x", gameRotationVectorValues[0]);
        data.put("y", gameRotationVectorValues[1]);
        data.put("z", gameRotationVectorValues[2]);
        data.put("cos", gameRotationVectorValues[3]);
        // data.put("headingAccuracy", gameRotationVectorValues[4]);
        break;
      case Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR:
        geomagneticRotationVectorValues = event.values.clone();
        data.put("x", geomagneticRotationVectorValues[0]);
        data.put("y", geomagneticRotationVectorValues[1]);
        data.put("z", geomagneticRotationVectorValues[2]);
        break;
      case Sensor.TYPE_GRAVITY:
        gravityValues = event.values.clone();
        data.put("x", gravityValues[0]);
        data.put("y", gravityValues[1]);
        data.put("z", gravityValues[2]);
        break;
      case Sensor.TYPE_GYROSCOPE:
        gyroscopeValues = event.values.clone();
        // from http://developer.android.com/reference/android/hardware/SensorEvent.html#values
        // http://www.kircherelectronics.com/blog/index.php/11-android/sensors/16-android-gyroscope-fusion

        // This timestep's delta rotation to be multiplied by the current rotation
        // after computing it from the gyro sample data.
        if (!hasInitialOrientation) {
          return;
        }
        // Initialization of the gyroscope based rotation matrix
        if (!stateInitializedCalibrated) {
          currentRotationMatrix =
              matrixMultiplication(currentRotationMatrix, initialRotationMatrix);
          stateInitializedCalibrated = true;
        }

        if (lastSensorGyroscopeEventTimestamp != 0 && stateInitializedCalibrated) {
          final float dT = (event.timestamp - lastSensorGyroscopeEventTimestamp) * NS2S;
          // Axis of the rotation sample, not normalized yet.
          float axisX = gyroscopeValues[0];
          float axisY = gyroscopeValues[1];
          float axisZ = gyroscopeValues[2];

          // Calculate the angular speed of the sample
          float omegaMagnitude = (float) Math.sqrt(axisX * axisX + axisY * axisY + axisZ * axisZ);

          // Normalize the rotation vector if it's big enough to get the axis
          if (omegaMagnitude > EPSILON) {
            axisX /= omegaMagnitude;
            axisY /= omegaMagnitude;
            axisZ /= omegaMagnitude;
          }

          // Integrate around this axis with the angular speed by the timestep
          // in order to get a delta rotation from this sample over the timestep
          // We will convert this axis-angle representation of the delta rotation
          // into a quaternion before turning it into the rotation matrix.
          float thetaOverTwo = omegaMagnitude * dT / 2.0f;
          float sinThetaOverTwo = (float) Math.sin(thetaOverTwo);
          float cosThetaOverTwo = (float) Math.cos(thetaOverTwo);
          deltaRotationVector[0] = sinThetaOverTwo * axisX;
          deltaRotationVector[1] = sinThetaOverTwo * axisY;
          deltaRotationVector[2] = sinThetaOverTwo * axisZ;
          deltaRotationVector[3] = cosThetaOverTwo;

          SensorManager.getRotationMatrixFromVector(deltaRotationMatrix, deltaRotationVector);
          // User code should concatenate the delta rotation we computed with the current rotation
          // in order to get the updated rotation.
          currentRotationMatrix = matrixMultiplication(currentRotationMatrix, deltaRotationMatrix);
          SensorManager.getOrientation(currentRotationMatrix, gyroscopeOrientation);

          data.put("x", gyroscopeValues[0]);
          data.put("y", gyroscopeValues[1]);
          data.put("z", gyroscopeValues[2]);
          data.put("radianX", gyroscopeOrientation[0]);
          data.put("radianY", gyroscopeOrientation[1]);
          data.put("radianZ", gyroscopeOrientation[2]);
          data.put("degreesX", Math.toDegrees(gyroscopeOrientation[0]));
          data.put("degreesY", Math.toDegrees(gyroscopeOrientation[1]));
          data.put("degreesZ", Math.toDegrees(gyroscopeOrientation[2]));
        }
        lastSensorGyroscopeEventTimestamp = event.timestamp;
        break;
      case Sensor.TYPE_GYROSCOPE_UNCALIBRATED:
        gyroscopeUncalibratedValues = event.values.clone();
        break;
        /*case Sensor.TYPE_HEART_RATE:
        heartRateValues = event.values.clone();
        data.put("rate", x);
        break;*/
      case Sensor.TYPE_LIGHT:
        lightValues = event.values.clone();
        data.put("lux", lightValues[0]);
        break;
      case Sensor.TYPE_LINEAR_ACCELERATION:
        linearAccelerationValues = event.values.clone();

        float x = linearAccelerationValues[0];
        float y = linearAccelerationValues[1];
        float z = linearAccelerationValues[2];

        data.put("x", x);
        data.put("y", y);
        data.put("z", z);
        break;
      case Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED:
        magneticFieldUncalibratedValues = event.values.clone();
        data.put("x_uncalib", magneticFieldUncalibratedValues[0]);
        data.put("y_uncalib", magneticFieldUncalibratedValues[1]);
        data.put("z_uncalib", magneticFieldUncalibratedValues[2]);
        data.put("x_bias", magneticFieldUncalibratedValues[3]);
        data.put("y_bias", magneticFieldUncalibratedValues[4]);
        data.put("z_bias", magneticFieldUncalibratedValues[5]);
        break;
      case Sensor.TYPE_PROXIMITY:
        proximityValues = event.values.clone();
        data.put("cm", proximityValues[0]);
        break;
      case Sensor.TYPE_RELATIVE_HUMIDITY:
        relativeHumidityValues = event.values.clone();
        data.put("percent", relativeHumidityValues[0]);
        break;
      case Sensor.TYPE_ROTATION_VECTOR:
        rotationVectorValues = event.values.clone();
        data.put("x", rotationVectorValues[0]);
        data.put("y", rotationVectorValues[1]);
        data.put("z", rotationVectorValues[2]);
        data.put("cos", rotationVectorValues[3]);
        data.put("headingAccuracy", rotationVectorValues[4]);
        break;
      case Sensor.TYPE_SIGNIFICANT_MOTION:
        significantMotionValues = event.values.clone();
        Log.i(LCAT, "TYPE_SIGNIFICANT_MOTION:" + significantMotionValues[0]);
        data.put("motion", significantMotionValues[0]);
        break;
      case Sensor.TYPE_STEP_COUNTER:
        stepCounterValues = event.values.clone();
        if (stepCounterOffset == 0) {
          stepCounterOffset = stepCounterValues[0];
        }
        data.put("val", stepCounterValues[0]);
        data.put("count", stepCounterValues[0] - stepCounterOffset);
        break;
      case Sensor.TYPE_ORIENTATION:
        orientationValues = event.values.clone();
        data.put("orientation", orientationValues[0]);
        data.put("pitch", orientationValues[1]);
        data.put("roll", orientationValues[2]);
        break;
      case Sensor.TYPE_STEP_DETECTOR:
        stepDetectorValues = event.values.clone();
        if (stepDetectorValues[0] == 1.0f) {
          stepDetectorCounter++;
        }
        data.put("count", stepDetectorCounter);
        break;
    }
    fireEvent(EVENT_UPDATE, data);
  }
예제 #25
0
  @Override
  public void onSensorChanged(SensorEvent event) {
    /**
     * X axis is horizontal and points to the right <br>
     * Y axis is vertical and points up <br>
     * Z axis points towards the outside of the front face of the screen
     *
     * <p>event.values <br>
     * - values[0] : x - values[1] : y - values[2] : z
     */
    synchronized (this) {
      float[] aData;
      float[] mData;

      int type = event.sensor.getType();
      if (type == Sensor.TYPE_ACCELEROMETER) {
        aData = mGData;
        for (int i = 0; i < 3; i++) aData[i] = event.values[i];
        if (mCount++ > 200) {
          LOG.d(TAG, "a_x: " + (aData[0]) + "  a_y: " + (aData[1]) + "  a_z: " + (aData[2]));

          // http://developer.android.com/reference/android/hardware/SensorEvent.html
          // According to this reference, when the device is sitting on a table, Acceleration minus
          // Gz on the z-axis is from 9.30 ~ 9.85 (It's not accurate!)
          if (aData[2] < 9.30 || aData[2] > 10.30) {
            Toast.makeText(mContext, "스마트폰을 수평으로 놔주세요!", Toast.LENGTH_SHORT).show();
          }
          mCount = 0;
        }
      } else if (type == Sensor.TYPE_MAGNETIC_FIELD) {
        mData = mMData;

        for (int i = 0; i < 3; i++) mData[i] = event.values[i];

        if (mCount2++ > 200) {
          LOG.d(TAG, "m_x: " + (mData[0]) + "  m_y: " + (mData[1]) + "  m_z: " + (mData[2]));
          mCount2 = 0;
        }
      }

      if (mCount3++ > 30) {

        SensorManager.getRotationMatrix(mR, null, mGData, mMData);
        SensorManager.getOrientation(mR, mOrientation);
        float azimuthInRadians = mOrientation[0];
        float azimuthInDegress = (float) (Math.toDegrees(azimuthInRadians) + 360) % 360;
        RotateAnimation ra =
            new RotateAnimation(
                mCurrentDegree,
                -azimuthInDegress,
                Animation.RELATIVE_TO_SELF,
                0.5f,
                Animation.RELATIVE_TO_SELF,
                0.5f);

        ra.setDuration(250);

        ra.setFillAfter(true);

        if (bearing != 0.0f) {
          // **** 15.07.02 additional function *****
          RotateAnimation ra2 =
              new RotateAnimation(
                  mCurrentDegree + bearing,
                  -azimuthInDegress + bearing,
                  Animation.RELATIVE_TO_SELF,
                  0.5f,
                  Animation.RELATIVE_TO_SELF,
                  0.5f);

          ra2.setDuration(250);

          ra2.setFillAfter(true);

          // 15.07.02 added canvas view
          canvasView.startAnimation(ra2);
        }

        compassView.startAnimation(ra);
        mCurrentDegree = -azimuthInDegress;

        mCount3 = 0;
      }
    }
  }
 // calculates orientation angles from accelerometer and magnetometer output
 public void calculateAccMagOrientation() {
   if (SensorManager.getRotationMatrix(rotationMatrix, null, accel, magnet)) {
     SensorManager.getOrientation(rotationMatrix, accMagOrientation);
   }
 }
예제 #27
0
  // It executes when the sensor change
  @Override
  public void onSensorChanged(SensorEvent event) {
    // Can change the accelerometer or the magnetometer
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) mGravity = event.values.clone();
    if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) mGeomagnetic = event.values.clone();

    // Need the data of both sensors for the compass
    if ((mGravity != null) && (mGeomagnetic != null)) {
      /*
       * For the orientation of the device, it calculates the azimut:
       * "angle of the reference (north) and a line in the middle of the observer
       * and the interest point in the same direction field" - Wikipedia
       * If the azimut is 0º, the device is oriented to the North, 90º to the East,
       * 180º to the South and 270º to the West
       *
       * For calculate the azimut, first calculate the rotation matrix (using the
       * accelerometer and magnetometer data) and after it uses this matrix obtaining
       * a vector that his first coordinate is de azimut
       */
      SensorManager.getRotationMatrix(rotationMatrix, null, mGravity, mGeomagnetic);
      SensorManager.getOrientation(rotationMatrix, orientation);

      float azimut = orientation[0]; // orientation contains: azimut, pitch and roll

      // Azimut to degrees
      float deviceOrientation = (float) (Math.toDegrees(azimut) + 360) % 360;

      boolean rightHeading = isInTheRightDirection(deviceOrientation);

      // changes the arrow color when the user is taking the good direction
      if (rightHeading) {
        int green = Color.parseColor("#008000"); // Green colour
        image.setColorFilter(green);
      } else {
        image.clearColorFilter();
      }

      // animate the image change for an smooth visualization
      RotateAnimation animation =
          new RotateAnimation(
              previusOrientation,
              -(deviceOrientation - providedOrientation),
              Animation.RELATIVE_TO_SELF,
              0.5f,
              Animation.RELATIVE_TO_SELF,
              0.5f);

      // how long the animation will take place
      animation.setDuration(210);

      // set the animation after the end of the reservation status
      animation.setFillAfter(true);

      tvHeading.setText(
          getString(R.string.compass_heading)
              + Float.toString((deviceOrientation - providedOrientation + 360) % 360)
              + getString(R.string.compass_degrees));

      // start the animation
      image.startAnimation(animation);

      // save the orientation for the next animation
      previusOrientation = -(deviceOrientation - providedOrientation);
    }
  }