我正在尝试为 TotalAccelerate 制作简单的移动平均线。简单地说,移动平均线应该采用 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)
答案 0 :(得分:0)
更改此行:
sensorText.setText((int) valueAfterMovingAverage);
为:
sensorText.setText(String.valueOf((int) valueAfterMovingAverage));