Java – Android: Getting data simultaneously from Accelerometer and Gyroscope

accelerometerandroidgyroscopejava

I'm having some issues getting data from the accelerometer and gyroscope simultaneously. I need to use these sensors to get acceleration and orientation in order to calculate relative position for a project I'm working on. When both sensors are used at the same time it leads to some very weird data output, in which the data only changes once every second. When only the accelerometer is run the data is not much better because it is only changing roughly 10 times a second on its fastest setting. This data is printed out to a file with a time stamp for each sensor reading.

I'm having trouble finding tutorials on the internet, particularly using more than one sensor together at the same time. Do I need to put each sensor on a different thread? I don't have much experience using threads, how could I do this.

Best Answer

You don't need to put each sensor on a different thread. Yo can use the class SensorManager to register and unregister the different sensors that you need

public class SensorActivity extends Activity, implements SensorEventListener {
 private final SensorManager mSensorManager;
 private final Sensor mAccelerometer;
 private final Sensor mGyroscope;

 public SensorActivity() {
     mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
     mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
     mGyroscope = mSensorManager.getDefaultSensor(TYPE_GYROSCOPE);
 }

 protected void onResume() {
     super.onResume();
     mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
     mSensorManager.registerListener(this, mGyroscope, SensorManager.SENSOR_DELAY_NORMAL);
 }

 protected void onPause() {
     super.onPause();
     mSensorManager.unregisterListener(this);
 }

Implements the sensorEventList handler (specially the method onSensorChanged) and check who belongs the received data:

 public void onSensorChanged(SensorEvent sensorEvent) {
    sensorName = sensorEvent.sensor.getName();
    Log.d(sensorName + ": X: " + sensorEvent.values[0] + "; Y: " + sensorEvent.values[1] + "; Z: " + sensorEvent.values[2] + ";");

}