0
我正在試圖做簡單移動平均爲總加速度。簡單地說,移動平均值應該採用TotalAccelerate矢量的4個樣本,並在運行時對其進行平均。然後移動一個樣本並平均下四個樣本,以此類推。 我寫的代碼不起作用。它因我不知道的原因而墜毀。我應該使用單獨的線程來做計算嗎?如果你寫一個僞代碼,我將不勝感激。移動加速度傳感器的平均方法
double TotalAccelerate;
ArrayList<Double> listPeaks;
//for Accelermeter
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorText = (TextView) findViewById(R.id.sensor);
accelermeter = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, accelermeter, SensorManager.SENSOR_DELAY_NORMAL);
mDetector = new GestureDetectorCompat(this, new MyGestureListener());
@Override
public final void onSensorChanged(SensorEvent event) {
// The light sensor returns a single value.
// Many sensors return 3 values, one for each axis.
//If my ToggleButton Ischecked and isListening=true.(at Oncreate method)
if (isListening) {
double xx = event.values[0];
double yy = event.values[1];
double zz = event.values[2];
//The result will be one vector of array
TotalAccelerate = Math.round(Math.sqrt(Math.pow(xx, 2)
+ Math.pow(yy, 2)
+ Math.pow(zz, 2)));
Log.i(DEBUG, "Accelerometer = " + TotalAccelerate);
listPeaks.add(TotalAccelerate);
//findPeaks(listPeaks);
Log.i(DEBUG, "list values " + listPeaks);
//Find moving average - window size= 4
MovingAverage ma = new MovingAverage(4);
ma.newNum(TotalAccelerate);
float valueAfterMovingAverage = (float) ma.getAvg();
sensorText.setText((int) valueAfterMovingAverage);
}
}
public Queue<Double> window = new LinkedList<Double>();
public int p;
public double sum;
///Moving Average class.
public class MovingAverage {
public MovingAverage(int period) {
assert period > 0 : "Period must be a positive integer";
p = period;
}
public void newNum(double num) {
sum += num;
window.add(num);
if (window.size() > p) {
sum -= window.remove();
}
}
public double getAvg() {
if (window.isEmpty()) return 0; // technically the average is undefined
return sum/window.size();
}
}
這是我得到的錯誤:
at android.content.res.Resources.getText(Resources.java:275)
at android.widget.TextView.setText(TextView.java:4264)
at com.example.arduinosensors.MainActivity.onSensorChanged(MainActivity.java:230)
at android.hardware.SystemSensorManager$SensorEventQueue.dispatchSensorEvent(SystemSensorManager.java:436)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:143)
at android.os.Looper.loop(Looper.java:122)
at android.app.ActivityThread.main(ActivityThread.java:5354)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
謝謝。它現在有效。 –