简体   繁体   中英

Direction of movement using an accelerometer android not working

I am developing an android application to get the direction of a android device.

I am using the code below:

 public class AccelerometerDirection  extends Activity implements SensorEventListener {
    TextView textView;
    StringBuilder builder = new StringBuilder();

    float [] history = new float[2];
    String [] direction = {"NONE","NONE"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        textView = new TextView(this);
        setContentView(textView);

        SensorManager manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Sensor accelerometer = manager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
        manager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {

        float xChange = history[0] - event.values[0];
        float yChange = history[1] - event.values[1];

        history[0] = event.values[0];
        history[1] = event.values[1];

        if (xChange > 2){
          direction[0] = "LEFT";
        }
        else if (xChange < -2){
          direction[0] = "RIGHT";
        }

        if (yChange > 2){
          direction[1] = "DOWN";
        }
        else if (yChange < -2){
          direction[1] = "UP";
        }

        builder.setLength(0);
        builder.append("x: ");
        builder.append(direction[0]);
        builder.append(" y: ");
        builder.append(direction[1]);

        textView.setText(builder.toString());
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // nothing to do here
    }
}

with reference to this How can I get the direction of movement using an accelerometer? .

But working is horrible and i am not getting the accurate value. I tried with different constant values, No use.any idea please share.

This line give you values at very high frequency at 50 HZ or 100 Hz for different devices

manager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);

So for every reading your output will change even when device is at rest because reading accelerometer not very accurate.

So either filter your readings with low pass filter or use reading at less frequency (say 1 HZ )

manager.registerListener(this, accelerometer, 1000000);

But lowpass filter is the best option to get smooth behaviour

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM