Thom Nichols

Avatar

Technology is evolution outside the gene pool

Smoothing Sensor Data with a Low-Pass Filter

If you search StackOverflow, there are a number of posts about Android sensor data being very jittery, and suggestions on implementing a smoothing algorithm.  Well not many people have actually posted a smoothing algorithm, and those that I have seen tend to be fairly complex.  

After some searching, I came to the Wikipedia entry for Low Pass Filter.  There's a pseudocode algorithm that I adapted for Java which works splendidly.  Not only that, but it's extremely simple.  The algorithm essentially requires tracking only two numbers - the prior number and the new number.  There's a constant, alpha, which affects the 'weight' or 'momentum' -- basically how drastically does the new value affect the current smoothed value.  Here's the full implementation:

	/*
	 * time smoothing constant for low-pass filter
	 * 0 ≤ alpha ≤ 1 ; a smaller value basically means more smoothing
	 * See: http://en.wikipedia.org/wiki/Low-pass_filter#Discrete-time_realization
	 */
	static final float ALPHA = 0.15f;

	/**
	 * @see http://en.wikipedia.org/wiki/Low-pass_filter#Algorithmic_implementation
	 * @see http://developer.android.com/reference/android/hardware/SensorEvent.html#values
	 */
	protected float[] lowPass( float[] input, float[] output ) {
		if ( output == null ) return input;
		
		for ( int i=0; i<input.length; i++ ) {
			output[i] = output[i] + ALPHA * (input[i] - output[i]);
		}
		return output;
	}

In my particular case, I used this to normalize raw accelerometer and magetometer sensor readings before calculating a compass bearing. Note that the input and output array elements are not sequential values, but completely separate dimensions (x,y,z) so e.g. each new x value is normalized against the smoothed x value, the new y with the smoothed y, etc.  This smoothing also has the curious effect of actually accelerating and decelerating the resulting output, e.g. if you quickly rotated the device 180 degrees.  Just like a physical compass needle would.  Neat!

Category: Android Java data

Add Comment

3 Comments

  1. avatar Re: Smoothing Sensor Data with a Low-Pass Filter 2011-10-01 Elektrophreak

    Cool! :-)
  2. avatar Re: Smoothing Sensor Data with a Low-Pass Filter 2011-10-26 Wolfgang

    Shouldn't be ALPHA somehow depend on the sampling rate?
  3. avatar Re: Smoothing Sensor Data with a Low-Pass Filter 2012-01-02 Dave Rose

    This works very well, thanks!  I'm implementing my own compass using the accelerometer and mag sensors.  However, all examples I've found are incomplete in some way.  Would you post your sensor handling code?  It would be appreciated.

Enter Your Comment