Search code examples
androidaccelerometeraverage

is there any way to force the accelerometer to update on a regular time interval?


Would it be possible say, to get the accelerometer to update 50 times a second? the reason I want to do this is is that I want to let the accelerometer run, collect all of the different values it records and then return an average.

I initially tried to just collect all of the different values

 yAverage = yAverage + new y; 

and then divide it by a counter that recorded the amount of different recordings.

 counter++;

both lines of code are in the "onSensorChanged" method and will always execute together (as in, if one executes the other will also execute without fail)

However the results I am getting are very inconsistent. if I have the phone lying flat on the table it will calculate almost random different values for the average even though the sensor value never changes and there for should always return the same.

Is there a better way to calculate the average?

I dont know if it matters but I am using floats to store the recorded values and doing the calculations.

Responce to Sherif: well there isnt really that much code in it, I have 3 float values that get the values from the acclerometer like so:

 y=event.values[1];

and it is located inside the "onSensorChanged" method inside the SensorEventListener.

I suppose the pseudo code would go like this:

 float yAverage = 0

 onSensorChanged{
    float y = event.values[1];
    if (y < 0){
       y = y * -1;
    }
    yAverage = yAverage + y;
    counter++;
 }

and then in another method it calculates;

 yAverage = yAverage / counter;

It then get's printed to the screen

it's not a complicated method but I just can't figure out why it is so inaccurate.


Solution

  • I have no idea if it is an execution error but I think it is a logical error

    SensorManager mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
    Sensor mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    
    mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
    public void onSensorChanged(SensorEvent event) {
        float y = event.values[1];
        if (y < 0){
            y = y * -1;
        }
    yAverage = yAverage + y;
    counter++; 
    }
    

    Summary:

    • make sure yAverage is global

    • make sure you're using TYPE_ACCELEROMETER

    • Don't forget that when put on a table you will get high values for value[1] due to gravity and Normal