我寫了下面的代碼,其中加速度計的值在旋轉期間以x,y,z顯示。加速度計值爲度數
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private TextView xText,yText,zText;
private Sensor mySensor;
private SensorManager SM;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating the Sensor Manager
SM = (SensorManager)getSystemService(SENSOR_SERVICE);
// Accelerometer Sensor
mySensor = SM.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
// Register sensor Listener
SM.registerListener(this, mySensor, SensorManager.SENSOR_DELAY_NORMAL);
// Assign TextView
xText = (TextView)findViewById(R.id.xText);
yText = (TextView)findViewById(R.id.yText);
zText = (TextView)findViewById(R.id.zText);
}
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
xText.setText("X: " + sensorEvent.values[0]);
yText.setText("Y: " + sensorEvent.values[1]);
zText.setText("Z: " + sensorEvent.values[2]);
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
}
現在我想將我從SensorEvents獲得的值轉換爲度數。我在這裏看到各種問題,但我感到困惑。
double x = sensorEvent.values[0];
double y = sensorEvent.values[1];
double z = sensorEvent.values[2];
應該有一個公式,它取上述值並將它們轉換成度。
任何想法?
謝謝,
泰奧。
編輯
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
//xText.setText("X: " + sensorEvent.values[0]);
//yText.setText("Y: " + sensorEvent.values[1]);
//zText.setText("Z: " + sensorEvent.values[2]);
double x = sensorEvent.values[0];
double y = sensorEvent.values[1];
double z = sensorEvent.values[2];
double pitch = Math.atan(x/Math.sqrt(Math.pow(y,2) + Math.pow(z,2)));
double roll = Math.atan(y/Math.sqrt(Math.pow(x,2) + Math.pow(z,2)));
//convert radians into degrees
pitch = pitch * (180.0/3.14);
roll = roll * (180.0/3.14) ;
yText.setText(String.valueOf(pitch));
zText.setText(String.valueOf(roll));
}
你有沒有運氣? –