package com.example.sensor01; import java.util.List; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.widget.TextView; public class MainActivity extends Activity implements SensorEventListener{ private static final float NS2S = 1.0f / 1000000000.0f; private float timestamp; private SensorManager mSensorManager; private TextView textview; private float angle2 = 0,angle0 = 0,angle1 = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textview = (TextView) findViewById(R.id.content); mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL); } @Override public void onAccuracyChanged(Sensor arg0, int arg1) { // TODO Auto-generated method stub } @Override public void onSensorChanged(SensorEvent event) { float[] values = new float[3]; if(0 != timestamp){ final float dT = (event.timestamp - timestamp) * NS2S; if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE){ //三个方向的角速度 values = event.values; } //三个方向转过的弧度 angle0 += values[0] * dT; angle1 += values[1] * dT; angle2 += values[2] * dT; //三个方向将弧度转换为角度,即 角度=弧度除以π再乘以180 弧度=角度乘以π后再除以180 float anglex = (float) Math.toDegrees(angle0);//前后垂直翻转的角度(相对于初始位置,即第一次取值) float angley = (float) Math.toDegrees(angle1);//左右翻转的角度(相对于初始位置,即第一次取值) float anglez = (float) Math.toDegrees(angle2);//左右摇摆的角度(相对于初始位置,即第一次取值) textview.setText(String.valueOf(anglex) + " " + String.valueOf(angley) + " " + String.valueOf(anglez)); } timestamp = event.timestamp; } }