amol junghare
amol junghare

Reputation: 73

Calculate angle in device when the device is held vertically

I want to calculate the angle between 0 to 45 degree when the device is held vertically (i.e., against a wall, with the bottom edge flat on a table).When tilt to right side it will captures the angle.For this I used senson manager & tried below code but it is not accurate. It only shows upto 5 degree.

    private void calculateAngle() {
    SensorManager sensorManager2 = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    this.sensorManager = sensorManager2;
    this.sensor = sensorManager2.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    SensorEventListener r0 = new SensorEventListener() {
        public void onAccuracyChanged(Sensor sensor, int i) {
        }
 public void onSensorChanged(SensorEvent sensorEvent) {
            if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                float f = sensorEvent.values[0]; // X-axis
                float f2 = sensorEvent.values[1]; // Y-axis
                float f3 = sensorEvent.values[2]; // Z-axis

                // Normalize the accelerometer values to the range -1 to 1
                float normalizedF = f / 9.8f;
                float normalizedF2 = f2 / 9.8f;
                float normalizedF3 = f3 / 9.8f;

                // Avoid zero values to prevent division by zero
                if (normalizedF2 == 0.0f) normalizedF2 = 0.01f;

                // Determine if the device is in a vertical position against a wall
                boolean isVertical = Math.abs(normalizedF2) > 0.8 && Math.abs(normalizedF3) < 0.2;

                if (isVertical) {
                    // Calculate the angle between the X and Y axes (rotation around Z-axis)
                    int angle = (int) ((Math.atan2(normalizedF, normalizedF2) * 180.0d) / Math.PI);
                    int absAngle = Math.abs(angle);

                    if (absAngle > 45) {
                        showAlert(); // Show alert if the angle exceeds 45 degrees
                    } else if (absAngle <= 45) {
                        customAlertDialog.setVisibility(View.GONE);
                        isAlertShown = false;
                        angleEt.setText(String.valueOf(absAngle)); // Display the angle
                    } else {
                        angleEt.setText("");
                        showAlert(); // Show alert if the angle exceeds 45 degrees
                    }
                } else {
                    // Clear the angle display when the device is not vertical
                    angleEt.setText("");
                    customAlertDialog.setVisibility(View.GONE);
                    isAlertShown = false;
                }
            }
        }



    };
    this.sensorEventListener = r0;
    this.sensorManager.registerListener(r0, this.sensor, 3);
}

Upvotes: 0

Views: 15

Answers (0)

Related Questions