gravitational acceleration calculate in android

142 views Asked by At

Hi this is my android code

  @Override
    public void onSensorChanged(final SensorEvent event) {

        //se l'evento generato è di tipo  MAGNETIC_FIELD
        if (event.sensor.getType() == Sensor.TYPE_GRAVITY) {

            DECIMAL_FORMATTER = new DecimalFormat("#.00");
            value.setText("X "+ DECIMAL_FORMATTER.format(event.values[0]) +"m/s2\n"+ "Y "+ DECIMAL_FORMATTER.format(event.values[1])+"m/s2\n"+ "Z "+ DECIMAL_FORMATTER.format(event.values[2])+"m/s2");


            TextView details = findViewById(R.id.details);

            details.setText(R.string.gravity_details);

            //invio evento ed attributi al metodo addEntry che aggiungerà gli elementi al grafico
            if (plotData) {
                addEntry(event);
                plotData = false;
            }
        }
    }

This code print the value of gravitational acceleration on 3 axis X Y and Z, but I want to print one value example 9,81 m/s2. What can I do?

1

There are 1 answers

0
Joni On

What you're looking for is called the magnitude or length of the acceleration vector. It can be computed with the Pythagorean formula, also see wikipedia:

double magnitude(float[] v) {
    return Math.sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
}

To use this method:

    double acceleration = magnitude(event.values);
    value.setText(DECIMAL_FORMATTER.format(acceleration) +"m/s2\n");