Search code examples
androidaccelerometersampling

Android accelerometer sampling rate/delay stabilization


I'm trying to detect the force strength of a tap by using the data from the accelerometer and with the method onTouch.

As far as I know, the fastest sampling frequency for the accelerometer is 200-202Hz, but this variability is giving me problems when trying to match the timestamps for the onTouch event and the peak in the accelerometer data.

Is there a way to stabilize the readings of the accelerometer to avoid this problem? Like controlling the specific thread or something?


Solution

  • If you want to match the hardware-provided time (event.timestamp) and the System time you can do this by adjusting the times.

    Usually the times are not the same, but they just differ by a constant amount of milliseconds. I suggest you to print out both times and compare them. You will then notice what the offset is:

    In my question, Ormi734 suggested to use the following code:

    private long timeDiff = 0l; // this will be used to adjust the offset between the times
    private boolean offsetDetermined = false;
    
    @Override
    public void onSensorChanged(SensorEvent event) {
    
        // just determine the offset once, since it should remain constant
        // you could also adjust it every n samples if it needs to be really accurate
        if (!offsetDetermined) {
            long MiliTime = System.currentTimeMillis();
            long NanoTime = event.timestamp;
            timeDiff = MiliTime - NanoTime / 1000000;
    
            log.info("Synchornizing sensor clock. Current time= " + MiliTime+ ", difference between clocks = " + timeDiff);
    
            offsetDetermined = true;
        }
    
        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];
        long ts = event.timestamp / 1000000 + timeDiff;
    
        // do your stuff here   
    }
    

    Accelerometer logger: experiencing occasional long delays between frames