我有一個程式,它從 Arduino UNO R3 讀取模擬資料并將該資料發送到其他設備,該設備讀取它并相應地執行一些操作。目前,每次我讀取資料時,它都會被發送出去,這會創建比執行任務所需的更多的資料點。因此,我想將資料集中在一個移動平均線中,然后發送。我的代碼現在看起來像這樣:
string forceAnalog = recieveData.Text;
recieveData.Clear();
var forceList = forceAnalog.ToUpper().Split(':').ToList();
foreach (var item in forceList)
if (item.Trim().StartsWith("X"))
{
textBoxX.Text = item.Remove(0, 1);
}
else if (item.Trim().StartsWith("Y"))
{
textBoxY.Text = item.Remove(0, 1);
}
else if (item.Trim().StartsWith("Z"))
{
textBoxZ.Text = item.Remove(0, 1);
}
string forceXanalog = textBoxX.Text;
string forceYanalog = textBoxY.Text;
string forceZanalog = textBoxZ.Text;
if (double.TryParse(forceXanalog, out forceX)) ;
if (double.TryParse(forceYanalog, out forceY)) ;
if (double.TryParse(forceZanalog, out forceZ)) ;
forceXvalue = (forceX * calibrationFactorX / 1023) - 5;
forceYvalue = (forceY * calibrationFactorY / 1023) - 5;
forceZvalue = (forceZ * calibrationFactorZ / 1023) - 50;
this.forceXlabel.Text = string.Format("{0:F2}", forceXvalue);
this.forceYlabel.Text = string.Format("{0:F2}", forceYvalue);
this.forceZlabel.Text = string.Format("{0:F2}", forceZvalue);
我從接收 Arduino 串行流的文本框中讀取資料,并從中創建 forceAnalog 字串。該字串包含 X、Y、Z 值,類似于:X-0.44 Y-0.15 Z-0.5 然后接收資料被清除并再次讀取這些值。然后通過一些計算將其發送到標簽。
What I want to to is, instead of reading, storing one set of X,Y,Z values and passing it along, I would like to read for example 5,10,100... sets of X,Y,Z values, then create an average from these and pass it along for calculations. How do I go about doing this?
uj5u.com熱心網友回復:
最簡單的選擇是累積 n 個專案,發送平均值,然后重置累加器和計數。對 Vector3 使用迭代器塊和 system.Numerics:
public static IEnumerable<Vector3> AverageN(
this IEnumerable<Vector3> highFrequencySamples,
int everNthSample)
{
var acc = Vector3.Zero;
var n = 0;
foreach (var sample in highFrequencySamples)
{
acc = sample;
n ;
if (n == everNthSample)
{
// Output the average since we have reached the number of samples needed
yield return acc / n;
acc = Vector3.Zero;
n = 0;
}
}
if (n > 0)
{
yield return acc / n;
}
}
雖然 Vector3 僅限于浮點數,但Vector3d使用雙精度創建等效項應該相當簡單。使用專用型別來捆綁坐標值往往會使您的代碼更簡單,因為您不必重復每個操作三次。如果他們設法發布諸如通用數學之類的東西,您可以制作這樣的通用方法,并適用于所有支持加法和除法的型別。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/457501.html
上一篇:System.IO.Directory.Exists在LINQ陳述句中失敗,但在foreach回圈中沒有
下一篇:你能用變數名做一個變數嗎?
