我正在尝试控制和LED与一个超声波传感器的距离计算的平均值。我有被平均的数据,但它从通电开始是连续的。我想在每十次读数后重新计算平均值。谁能告诉我,我需要改变什么来重新计算每10个值的平均值,而不是计算一个运行平均值?
const int TrigPin = 8;
const int EchoPin = 9;
const int LedPin = 13;
const int numReadings = 5;
long Duration = 0;
int readings[numReadings];
int index = 0;
int total = 0;
int average = 0;
void setup() {
Serial.begin(9600);
pinMode(LedPin, OUTPUT);
pinMode(TrigPin, OUTPUT);
pinMode(EchoPin, INPUT);
for (int thisReading = 0; thisReading < numReadings; thisReading++)
readings[thisReading] = 0;
}
void loop() {
digitalWrite(TrigPin, LOW);
delayMicroseconds(2);
digitalWrite(TrigPin, HIGH);
delayMicroseconds(10);
digitalWrite(TrigPin, LOW);
Duration = pulseIn(EchoPin, HIGH);
long Distance_mm = Distance(Duration);
//Serial.print("Distance = ");
//Serial.print(Distance_mm);
//Serial.println(" mm");
total= total - readings[index];
readings[index] = analogRead(EchoPin);
total = total + readings[index];
index = index + 1;
if (index >= numReadings)
index = 0;
average = total / numReadings;
Serial.print("Dist_avg = ");
Serial.print(average);
Serial.println("mm");
delay(100);
if (average > 400)
{
digitalWrite(LedPin, HIGH); // turn the LED on (HIGH is the voltage level)
}
else
{
digitalWrite(LedPin, LOW); // turn the LED off by making the voltage LOW
}
}
long Distance(long time)
{
long DistanceCalc;
DistanceCalc = ((time /2.9) / 2);
return DistanceCalc;
}发布于 2014-02-08 08:00:47
你只需要修改你的代码,这样当索引==为10时,它就会计算出平均值。如果你将numReadings修改为10,你可以尝试这样的代码:
void loop(){
...
//total= total - readings[index];
//you don't need the array here anymore
//readings[index] = analogRead(EchoPin);
//total = total + readings[index];
total = total + analogRead(EchoPin);
index = index + 1;
if (index >= numReadings)
{
index = 0;
average = total / numReadings;
Serial.print("Dist_avg = ");
Serial.print(average);
Serial.println("mm");
delay(100);
if (average > 400)
digitalWrite(LedPin, HIGH); // turn the LED on (HIGH is the voltage level)
else
digitalWrite(LedPin, LOW); // turn the LED off by making the voltage LOW
total = 0;
}发布于 2014-06-12 01:10:49
你想在每次阅读后计算最后10个读数的平均值,还是每10个读数计算平均值。在第一种情况下,你需要一个“旋转数组”,在第二种情况下,你不需要一个数组,只需将total设置为零,对读数进行计数,将读数与总数相加,然后每当计数达到10时,输出平均值,并再次将总数设置为零。
发布于 2014-11-05 16:31:27
只是添加这个链接作为参考,这告诉你不应该平均声纳数据。http://forum.arduino.cc/index.php/topic,20920.0.html
https://stackoverflow.com/questions/21639725
复制相似问题