1. In the use of sensors, we often need to organize sensor data in various ways to make the application achieve better results. Here are some common simple processing methods:
1. Weighted smoothing: smooth and equalize sensor data to reduce accidental The impact of data mutation;
2. Extract mutation: remove static and slowly changing data backgrounds, emphasizing instantaneous changes;
3. Simple moving average: retain the latest K data in the data stream and take the average;
Second, the weighted smoothing
algorithm is as follows:
(new value) = (old value) * (1 - a) + X * a
Where a is the set weight, X is the latest data, the program is implemented as follows:
float ALPHA = 0.1f; public void onSensorChanged(SensorEvent event){ x = event.values[0]; y = event.values[1]; z = event.values[2]; mLowPassX = lowPass(x,mLowPassX); mLowPassY = lowPass(x,mLowPassY); mLowPassZ = lowPass(x,mLowPassZ); } private float lowPass(float current,float last){ return last * (1.0f - ALPHA) + current * ALPHA; }
3. Extract mutation
Use the inverse algorithm of the above weighted smoothing.
The implementation code is as follows:
public void onSensorChanged(SensorEvent event){ final float ALPHA = 0.8; gravity[0] = ALPHA * gravity[0] + (1-ALPHA) * event.values[0]; gravity[1] = ALPHA * gravity[1] + (1-ALPHA) * event.values[1]; gravity[2] = ALPHA * gravity[2] + (1-ALPHA) * event.values[2]; filteredValues[0] = event.values[0] - gravity[0]; filteredValues[1] = event.values[1] - gravity[1]; filteredValues[2] = event.values[2] - gravity[2]; }
4. Simple moving average
retains the most recent K data in the sensor data stream and returns their average value. k represents the size of the average "window"; the
implementation code is as follows:
public class MovingAverage{ private float circularBuffer[]; //Save the latest K data of the sensor private float avg; //return to sensor average private float sum; //sum of sensor data in the value private float circularIndex; //Sensor data array node position private int count; public MovingAverage(int k){ circularBuffer = new float[k]; count= 0; circularIndex = 0; avg = 0; sum = 0; } public float getValue(){ return arg; } public long getCount(){ return count; } private void primeBuffer(float val){ for(int i=0;i circularBuffer[i] = val; sum += val; } } private int nextIndex (int curIndex) { if(curIndex + 1 >= circularBuffer.length){ return 0; } return curIndex + 1; } public void pushValue(float x){ if(0 == count++){ primeBuffer (x); } float lastValue = circularBuffer[circularIndex]; circularBuffer[circularIndex] = x; //Update the sensor data in the window sum -= lastValue; //Update the sensor data in the window and sum += x; avg = sum / circularBuffer.length; // Calculated sensor average circularIndex = nextIndex(circularIndex); } }
5. Remarks
Reference: "Android Sensor Advanced Programming"
Article source: http://blog.csdn.net/u011630458