All Articles

(Archived) Smoothing out sensor values from SensorEvents, specifically for Orientation, in Android

Note: This is an archived post from my previous blog. It can also be found on WaybackMachine. -John

For my EnschedeLocator app, I want the user to get a compass needle that points towards the destination address using the device’s orientation sensor and the calculated bearing between the user’s location and his destination. For this, I implemented and tweaked Google’s Compass example.

However, the compass seemed very jittery and unreliable, and frustration ensued. The simple solution came via this StackOverflow thread. Simply store a number of recent values and average them. This simple fix made the needle rotate smoothly and stay on target.

/**Tweaked method for setting an average value. Pass the compassAverage to canvas.rotate()*/
public void setmValues(float[] mValues) {
  this.mValues = mValues;
  compassValues[0]= compassValues[1];
  compassValues[1]= compassValues[2];
  compassValues[2]= compassValues[3];
  compassValues[3]= compassValues[4];
  compassAverage = (compassValues[0] +compassValues[+compassValues[2] +compassValues[3] +compassValues[4])/5;